reactjs - 为什么 mapStateToProps 会重新渲染,也就是说在 Component 中调用 render()
问题描述
我认为在反应框架中,视图会随着 Component 的变化而变化
state
,所以我认为在
mapStateToProps
运行时,组件会得到一个新的store's
state
,这意味着
props
组件的变化。根据
react
frame ,在这种情况下,视图不会重新渲染,除非this.setState
调用
解决方案
我举一个例子。
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 商店中更改的新道具更新您的本地状态。
推荐阅读
- excel - 在 Power BI 中,如何更新 Excel 文件中的分析以使用更新后的度量?
- node.js - MongoDB 更新: CastError: Cast to ObjectId failed for value
- mysql - case语句-如何在MYSQL中实现目标格式?
- html - 除了第一个手风琴之外,Bootstrap 手风琴不会开始关闭
- java - 线程“AWT-EventQueue-0”中的异常 java.lang.NullPointerException [Dijkstra]
- c# - 在继续执行代码之前等待面板上的 KeyDown
- sql - 具有逻辑操作的高性能 SQL 标签搜索查询
- wordpress - 如何将属性传递给 InnerBlocks 模板中的子 Gutenberg 块?
- javascript - 使用 DataTables,我从 API 中获取 HTML 字符串,但表格单元格显示“
你好
" 而不是 ap 标签中的 "Hello"。做什么? - python-3.x - 从环境中检索凭据时出错:在配置文件中引用的 credential_source 中找不到凭据