【发布时间】:2017-03-12 13:32:34
【问题描述】:
在我的其他课程中,componentWillReceiveProps 运行良好,但由于某种原因,它没有在这里触发。
ItemView.jsx
class ItemView extends React.Component {
constructor(props) {
super(props);
this.state = {
name: null,
rating: null,
sector: null,
location: null,
description: null,
image: "blank.png",
show: false
};
}
...
componentWillReceiveProps(nextProps) {
if(!nextProps.companyToRender) {
this.setState({
name: null,
rating: null,
sector: null,
location: null,
description: null,
image: "blank.png",
show: false
});
}
else {
var companyToRender = nextProps.companyToRender;
this.setState({
name: companyToRender.name,
rating: companyToRender.rating,
sector: companyToRender.sector,
location: companyToRender.location,
description: companyToRender.description,
image: companyToRender.image,
show: true
});
}
...
render () {
return(
<div>
...
<CommentBox show={this.state.show} companyToRender={this.state.name}/>
...
</div>
);
}
}
评论框.jsx
class CommentBox extends React.Component {
constructor(props) {
super(props);
this.state = {companyToRender: null};
}
componentWillReceiveProps(nextProps) {
this.setState({companyToRender: nextProps.companyToRender});
}
...
}
如果不传递任何内容,则传递给 itemView 的 prop 为 null,或者 ItemView 分配给它的数组。
componentWillReceiveProps() 仅在状态的属性变为 null 时触发,而不是在设置时触发。 ( (null --> entry) 不起作用,但 (entry --> null) 起作用)。
我错过了什么吗?谢谢!
-- 编辑:
(null --> entry) 更新状态,但不调用日志或任何后续 componentWillRecieveProps()。 (但 entry --> null 可以。)
【问题讨论】:
-
您是否在
ItemView的componentWillReceiveProps或通过chrome 的react检查器插件验证name状态设置正确?听起来`ItemView` 没有重新渲染,因为name没有改变。 -
我尝试在 componentWillReceiveProps() 函数和 CommentBox.jsx 的 render() 函数中记录。奇怪的是,它并没有打印出 componentWilRecieveProps() 中的日志,而是在 null-->entry 期间更改了 render() 中的状态。我将更新条目以在 chrome 上显示输出。
-
"如果不传递任何内容,传递给 itemView 的 prop 要么为 null,要么为 ItemView 分配给它的数组。"这只是您的问题中的一个错误,还是
companyToRender是一个数组(如您所说)?我想它应该是一个对象。另外,请注意 componentWillReceiveProps 在组件首次安装时不会被调用(但仅在之后)。