【问题标题】:Can't dispatch action in class component无法在类组件中调度动作
【发布时间】:2021-09-08 13:37:32
【问题描述】:
// action
export const getEvents = () => async (dispatch) => {
  try {
    dispatch({ type: GET_EVENTS_REQUEST })
    const data = await axios.get('http://localhost:5000/api/schedule').then((response) => response.data)
    dispatch({ type: GET_EVENTS_SUCCESS, payload: data })
  } catch (error) {
    dispatch({
      type: GET_EVENTS_FAIL,
      payload:
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message,
    })
  }
}

// reducer
export const getEventsReducer = (state = { event: [] }, action) => {
  switch (action.type) {
  case GET_EVENTS_REQUEST:
    return { loading: true }
  case GET_EVENTS_SUCCESS:
    return { loading: false, event: action.payload }
  case GET_EVENTS_FAIL:
    return { loading: false, error: action.payload }
  default:
    return state
  }
}

// and this is how I'm trying to call my action:
import { getEvents } from '../../redux/actions/calendarActions'

class Calendar extends React.PureComponent {
    componentDidMount() {
        const { dispatch } = this.props
        console.log(dispatch(getEvents()))
    }
}
export default connect()(Calendar)
// component is much bigger, I only added relevant parts

直到我的 reducer,如果我 console.log 我的数据,它是正确的,以及在我的 redux 开发工具选项卡中:一个包含一些条目的数组。但是当 console.logging 在我的日历组件中时,它会返回一个带有未定义结果的承诺:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

我做错了什么?

【问题讨论】:

  • getEvents 确实返回 undefined
  • 你在使用redux-thunk吗?如果没有,你应该。它是一个中间件,可让您分派异步操作。另外,您没有 await 调度,所以它当然会返回 Promise
  • 这正是 redux(和一般状态)的工作原理。与您无法通过控制台记录this.setState 的结果相同的方式。相反,更新会触发重新渲染,您可以在其中获取更新后的值作为道具(假设连接正确)。
  • @RonB。等待dispatch 毫无意义,它不会返回任何东西。承诺是因为 getEvents 是异步的。
  • @RonB。我正在使用 redux-thunk 并将其添加到我的商店中

标签: reactjs react-redux dispatch


【解决方案1】:

通常您希望访问组件中 Redux 的调度或存储。你已经在组件中拥有了 dispatch 函数,但是如果你需要访问其中的 Redux 状态:

首先你需要定义这样的函数,这使得redux store在组件中可用。

    const mapStateToProps = (state) => ({
  state: state // a "state" prop is available in the component which points to redux state, 
})

如果只需要 Redux 状态的某些属性,也可以自定义:

        const mapStateToProps = (state) => ({
  state: state.event // 
})

并像这样更改连接功能:

connect(mapStateToProps)(Calendar)

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多