动作不叫减速器

时间:2019-11-19 09:19:14

标签: reactjs redux axios

我正在使用react-redux,问题是我的动作之一没有调度到reducer 这是我的代码:

Actions.js:

export const getRooms = () => {
  console.log('reach action')
  const config = {
    headers: {
      Authorization: localStorage.getItem('lets_chat_token')
    }
  }
  return dispatch => {
    console.log('in dispatch')
    return axios
      .get(`/api/rooms`, config)
      .then(data =>
        dispatch({
          type: 'GET_ROOMS',
          payload: data.data.data
        })
      )
      .catch(err =>
        dispatch({
          type: 'ERROR',
          payload: err
        })
      )
  }
}

我在react组件中调用此操作:

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getRooms } from '../../Redux/Actions'

import './Connections-list.css'

class ConnectionsList extends Component {
  handleRooms = () => {
    getRooms()
  }

  render() {
    return (
      <div className="connections-list-container">
        <div className="connections-list-header">
          <i className="fas fa-users" onClick={this.handleRooms}></i>
          <i className="fas fa-user-friends"> </i>
        </div>
        <div className="connections-list-list">aasa</div>
      </div>
    )
  }
}

export default connect(
  null,
  { getRooms }
)(ConnectionsList)

问题在于第一个日志出现在getRooms()函数中:

console.log('reach action')

但是此后什么也没发生。

注意:我正在使用redux-thunk。我还有其他一些效果很好的动作。

1 个答案:

答案 0 :(得分:2)

您需要绑定您的redux动作,然后将其放入道具中。下面是修改后的代码。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux' // bind redux action with dispatch
import { getRooms } from '../../Redux/Actions'

import './Connections-list.css'

class ConnectionsList extends Component {
  handleRooms = () => {
    const { getRooms } = this.props //get the redux action from props
    getRooms()
  }

  render() {
    return (
      <div className="connections-list-container">
        <div className="connections-list-header">
          <i className="fas fa-users" onClick={this.handleRooms}></i>
          <i className="fas fa-user-friends"> </i>
        </div>
        <div className="connections-list-list">aasa</div>
      </div>
    )
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators({getRooms}, dispatch)
}

export default connect(
  null,
  mapDispatchToProps
)(ConnectionsList)