在我的其他课程中,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>
);
}
}
评论框组件 CommentBox.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分配给它的数组。
当状态属性变为null时,componentWillReceiveProps()才会触发,而不是当它被设置时。((null --> entry)无效,但(entry --> null)有效)。
我是否漏掉了什么?谢谢!
-- 编辑:
(null --> entry)更新状态,但不调用日志或任何后续的componentWillRecieveProps()。(但entry --> null会)
ItemView
的componentWillReceiveProps
或通过Chrome的react
检查器插件验证了name
状态是否被正确设置?这听起来像是ItemView
没有重新渲染,因为name
没有改变。 - Rose RobertsoncompanyToRender
是一个数组(如你所说)?我猜应该是一个对象。 此外,请注意当组件初次挂载时,componentWillReceiveProps方法不会被调用(只有之后才会调用)。 - fabio.sussetto