在我的其他课程中,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) 起作用)。
我错过了什么吗?谢谢!
--
edit:
(null -->entry) 更新状态,但不调用日志或任何后续的 componentWillRecieveProps()。 (但是 Entry --> null 确实如此。)
null 的日志 --> 条目 https://i.stack.imgur.com/JcfId.png
条目日志 --> null https://i.stack.imgur.com/4L1DP.png