javascript - 反应子状态不会使用父亲的道具更新(并且在分支中更深)
问题描述
问题如下:我有组件:祖父,父亲和孩子(字面意思是:D)。祖父通过道具将他的状态传递给父亲(父亲用它设置他的状态)。然后父亲将道具传递给孩子,孩子也用它设置状态。当我显示 this.props 时,一切都很好,但是当我显示状态时,我看到父亲和孩子没有任何变化。我听说有类似 componentWillReceiveProps() 的东西,但它已经被弃用了。
工作示例:https ://codesandbox.io/s/doesitworkornot-rrcgt?fontsize=14&hidenavigation=1&theme=dark
和代码:
祖父.js
import React from "react";
import Father from "./Father";
class GrandFather extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: 1
};
}
onClick = e => {
this.setState(prevState => ({
clickedCounter: prevState.clickedCounter + 1
}));
};
render() {
return (
<div>
<button onClick={this.onClick}>Press me</button> <br />
Here is Grandfather -> state value={this.state.clickedCounter}
<Father clickedCounter={this.state.clickedCounter} />
</div>
);
}
}
export default GrandFather;
父亲.js
import React from "react";
import Child from "./Child";
class Father extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: this.props.clickedCounter
};
}
render() {
return (
<div>
Here is Father -> props value={this.props.clickedCounter} <br />
Here is Father -> state value={this.state.clickedCounter}
<Child clickedCounter={this.props.clickedCounter} />
</div>
);
}
}
export default Father;
Child.js
import React from "react";
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: this.props.clickedCounter
};
}
render() {
return (
<div>
Here is Child -> props value={this.props.clickedCounter} <br />
Here is Child -> state value={this.state.clickedCounter}
</div>
);
}
}
export default Child;
我还听说有类似克隆孩子的事情......如果可能的话,我想避免它。
解决方案
当你从 props 初始化 state 时,react 不会刷新 state,但它会刷新 props。您可以使用以下代码代替 componentWillReceiveProps 使其工作。
static getDerivedStateFromProps(nextProps) {
return {
clickedCounter: nextProps.clickedCounter,
}
}
推荐阅读
- python - 使用 cogs 的不和谐问候,on_member_join 不起作用
- algorithm - 如何计算由三角形网格定义的空心物体的惯性张量?
- java - 如何将多个用户连接在一起并发送每个连接的用户信息?(爪哇)
- python - 尝试按年龄组对输入进行排序时出现“浮动”错误
- kotlin - 如何使用 KotlinPoet 为 PropertySpec 获取正确的 TypeName
- prestashop-1.7 - 在购物车中查看产品类别 Prestashop 1.7
- python - 具有 pop() 方法的自定义类未返回正确的新列表长度
- c++ - Visual Studio 2019 - 如何使用多个预编译头文件设置项目
- reactjs - 在迭代中插入列表数据(地图)
- tensorflow - 是否可以在 keras 功能 API 中为训练和测试添加不同的行为