Redux:无法读取未定义的属性'then'

时间:2017-07-03 09:56:39

标签: reactjs redux react-redux

我正在尝试在mapDispatchToProps中组合操作。尝试获取数据并在启动模式对话框后。但我一直在无法读取属性'然后'未定义错误。

有人可以解释一下,我做错了什么?

mapDispatchToProps:

const mapDispatchToProps = dispatch => ({
  onClick: id => {
    // console.log(fetchThing(id)) returns undefined
    dispatch(fetchThing(id)).then(() => {
      dispatch(showModal())
    })
  }
})

Redux行动:

export const fetchThing = () => {
  const request = axios.get(URL_API)

  return dispatch => {
    request.then(response => {
      dispatch({ type: ACTION_FETCH, payload: response.data })
    })
  }
}

2 个答案:

答案 0 :(得分:0)

为什么不使用redux-thunk?有了它,你可以这样写你的行动:

export const fetchThing = dispatch => axios.get(URL_API)
  .then(response => dispatch({ type: ACTION_FETCH, payload: response.data }))

Redux thunk中间件将为您完成所有工作,每次您需要mapDispatchToProps内的异步操作时,您都不需要这样做。

答案 1 :(得分:0)

mapDispatchToProps不应该有副作用。这应该只顾名思义,并将动作连接到redux。这应该是:

const mapDispatchToProps = {
  fetchThing: yourAction.fetchThing,
  showModal: yourAction.showModal,
};

export default connect(null, mapDispatchToProps)(YourComponent);

然后在你的(可能)按钮中:

<button type="button" onClick={this.handleClick} />

// this can be an asynchronous function, or you can just handle it in the action.
handleClick = async id => {
  await this.props.fetchThing(id);
  this.props.showModal();
};