我有一个 React 组件:stepA,它在提交时获取一个值,然后将其作为 state.chef_positions.[0].chef_title_id
存储在我的 redux 存储中。
用户提交步骤 A 后,他们会立即定向到步骤 B。 StepB 在stepA 的reducer 完成之前挂载,这意味着StepB 正在从存储中加载不正确的值。
当步骤A用户操作已保存到服务器/存储时,让步骤B重新渲染的正确方法是什么?重新渲染它的调度已完成?
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);
最佳答案
实际上,没什么。
由于 Redux 连接到 React 应用程序的方式是通过“一流对象”级别(您将 mapStateToProps 连接到组件),因此当存储发生更改时,组件中的 props 会被修改为当前存储状态.
您唯一需要做的就是使用 { componentDidUpdate } 生命周期方法重新分配“title_id”/在使用 title_id 的地方直接使用“this.props ...”/使用“useSelector”redux hook。
另一件事,您可以将 {mapDispatchToProps } 添加到连接
关于reactjs - 如何让 React 组件检测状态对象何时更改并重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403403/