首页 > 解决方案 > 为什么 mapStateToProps 会重新渲染,也就是说在 Component 中调用 render()

问题描述

标签: reactjsreduxreact-redux

解决方案


我举一个例子。

1)你首先加载你的组件

2)您对组件进行更改,从而更改该组件的 redux 状态

现在,如果您想查看与此组件关联的新道具,您将在您的“render()”方法中看到它们。这是因为如果 props 发生变化,react 组件将自动重新渲染(如 Peter Ambruzs 所述)。问题是,如果你想在你的渲染函数之外使用这些新的道具,你将不得不更新你的道具(或你的本地状态)。

在这种情况下,您应该使用 getDerivedStateFromProps(新的 componentWillReceiveProps),例如:

constructor(props) {
  super(props);
  state = {
    stateExample: this.props,
  }
}

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.stateExample !== prevState.stateExample) {
    return { stateExample: nextProps.stateExample }
  } else return null;
}

这将使用您刚刚在 redux 商店中更改的新道具更新您的本地状态。


推荐阅读