reactjs - 在 ReactJS 中正确更新孩子的状态
问题描述
我发现我的状态没有正确更新。如果您看到下面的代码console.log(this.props.clickedImage)
给出了我期望的值,但console.log(this.state.items);
不是。
我正在使用componentWillReceiveProps()
它来更新它,但我不确定这是否是好方法。最好的方法是什么?
家长:
constructor(props){
super(props);
// set the state to handle which of the panes displays the information you want
this.handleChildClick = this.handleChildClick.bind(this),
this.state= {
clickedItem: 'none',
};
}
handleChildClick(src) {
this.setState({ clickedItem: src });
}
render() {
return (
<div className="ao">
<CharacterForm clickedImage={this.state.clickedItem}/>
<SearchForm image_clicked={this.handleChildClick}/>
</div>
);
}
孩子甲:
constructor(props) {
super(props);
this.state = {
items: [
{ name: "one", divStyle: this.props.clickedImage},
{ name: "two", divStyle: this.props.clickedImage},
{ name: "three", divStyle: this.props.clickedImage},
]
};
}
componentWillReceiveProps(nextProps){
if(nextProps.itemsLeft !==this.props.clickedImage){
this.setState({
})
}
}
render() {
console.log(this.props.clickedImage);
console.log(this.state.items);
return this.state.itemsRight.map(item => (
<FrameCharacter key={item.name} item={item} />
));
}
孩子乙:
render() {
<img src="../images/misc/eq.png" onClick={() => image_clicked(eq.image)}/>
}
解决方案
componentWillReceiveProps
已弃用。getDerivedStateFromProps
这种情况就是引入钩子的确切原因。它允许从 props 派生状态,包括最初在构造函数中收到的那些:
static getDerivedStateFromProps(props, state) {
return {
items: [
{ name: "one", divStyle: props.clickedImage }
...
];
}
}
请注意,这props
是getDerivedStateFromProps
. 如果需要访问以前的clickedImage
道具来完全替换componentWillReceiveProps
,clickedImage
也可以存储到状态中。
推荐阅读
- python - Django F() 表达式在函数参数中不起作用
- python - 创建类实例的 Python 函数
- haskell - 无法将类型 'Either String' 与 '[]' 匹配
- python - os.execl() 中第二个参数的用途是什么
- spring - 我想在全球范围内返回关于未处理异常的 400 而不是 500 的状态代码
- html - CSS 选择器特异性计算:类与元素
- html - CSS 边框过渡添加了不需要的额外像素
- etl - 花 ETL 状态成功但结果为假
- django - 在 Kubernetes 中使用 Gunicorn 在 Nginx 上运行 Django 是个好主意吗?
- php - 胜率计算 - 来自 Leaguepedia 的 Php 和 api