redux mapStateToProps在空状态的情况下调用ajax

问题描述 投票:1回答:2

redux中使用react,如何从mapStateToProps函数内部调度动作?

class Example React.Component {
  render(){return (
    <div>
      Hello {this.state.userData.name} <--
    </div>)};
);

Example.propTypes = {
  id: PropTypes.number.isRequired,
};

function select(state,ownProps) {
  let userData = state.user[ownProps.id];
  if(!userData){//if not already in store then i want to load it
    ///I WANT TO dispatch an action that load this user from server.
    //dispatch({type:'LOAD_USER',id: ownProps.id});
  }
  return {
    userData
  };
}

export default connect(select)(Example);

//example usage <Example id="1" /> //should return state.user[1].name
reactjs redux react-redux jsx
2个回答
0
投票

由于组件呈现非常依赖于ajax调用的用户数据,因此调度的正确位置是componentWillReceiveProps

如果你已经将mapDispatchToProps回调传递给connect(),那么你应该能够在this.props.actions.anyAction()中调用componentWillReceiveProps

如果你在没有传递第二个参数(connect())的情况下调用了mapDispatchToProps,那么你必须明确地调用this.props.dispatch()


0
投票

我强烈建议使用sagas进行异步任务。有这个动作的传奇手表。如果它看到一个,让它检查用户是否在商店。如果他不在商店中,请进行异步操作以获取它,将其添加到商店,然后重播上一个操作。

© www.soinside.com 2019 - 2024. All rights reserved.