如何让React组件检测状态对象何时更改并重新呈现?

时间:2017-06-07 04:18:06

标签: reactjs redux react-redux

我有一个react组件:stepA,它在submit上获取一个值,然后将其作为state.chef_positions存储在我的redux商店中。[0] .chef_title_id

用户提交StepA后,会立即将其导向StepB。在stepA的reducer完成之前,StepB正在安装...意味着StepB正在从商店加载一个不正确的值。

当stepA用户操作已保存到服务器/商店时,将stepB重新呈现的正确方法是什么...重新呈现它的调度已完成...

由于

class stepA extends React.Component {

  handleSubmit(data) {
    this.props.actions.createChefPosition(data);
    this.props.nextStep();
  }

...


class stepB extends React.Component {

  componentDidMount() {
    const title_id = this.props.chef_positions[0].chef_title_id;
    this.props.dispatch(loadChefTitleSkills(chef_title_id));
  }

  stepB.propTypes = {
    chef_positions: PropTypes.array.isRequired,
  };

  function mapStateToProps(state, ownProps) {
    return {
      chef_positions: state.chef_positions,
    };
  }

export default connect(mapStateToProps)(stepB);

1 个答案:

答案 0 :(得分:0)

实际上,什么都没有。

由于Redux通过“一流对象”级别(您将mapStateToProps连接到您的组件)连接到React应用,因此当商店发生更改时,组件中的道具会被修改为当前商店状态

您唯一需要做的就是使用{componentDidUpdate}生命周期方法重新分配“ title_id” /在使用title_id的任何地方直接使用“ this.props ...” /使用reduse钩子使用“ useSelector”。

另一件事,您可以将{mapDispatchToProps}添加到连接