当我的代码运行时,它会不断循环 ComponentDidUpdate()
。所以我的问题是我应该使用什么生命周期方法?因为它正在循环,因为我的组件在渲染中重复调用它,对吧?或者这是一个错误的假设?我尝试了 ComponentWillMount() ,但每次都会渲染一个空数组。
组件
const NetflixTile = ({ videos }) => {
console.log("In tile " + JSON.stringify(videos));
if (videos.length != 0) {
for (let i = 0; videos.length > i; i++) {
console.log();
return (
<div className="row__inner">
<div className="tile">
<div className="tile__media">
<img
className="tile__img"
id="thumbnail"
src="this.state.penis"
alt=""
/>
</div>
</div>
</div>
);
}
} else {
return (
<div>
<h1>
You have not yet uploaded any STEM content. Go to your dashboard page
and click Upload to add to this library.
</h1>
</div>
);
}
};
export default NetflixTile;
渲染类
构造函数
constructor(props) {
super(props);
this.props.getVideos();
this.state = {
thumbnail: []
};
}
渲染片段
return (
<div className="explore">
<div className="row">
<NetflixTile videos={this.state.thumbnail} />
</div>
</div>
);
ComponentDidUpdate
componentDidUpdate(prevState) {
console.log("Current State->" + this.state.thumbnail);
console.log("Previous State->" + prevState.thumbnail);
if (this.props.videos == null) {
console.log("It's null");
} else {
if (this.state !== prevState) {
const videos = this.props.videos.video.map(video => {
this.setState(prevState => ({
thumbnail: [...prevState.thumbnail, video.thumbnail]
}));
console.log(this.state.thumbnail);
});
}
}
}
编辑
我按照建议更改了 componentDidUpdate,但无法弄清楚为什么 this.state.thumbnail
返回时甚至没有一个数组。 prevState.thumbnail
只是未定义。如果我只执行 prevState
它确实会返回对象。
最佳答案
React 文档说:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
这对您很重要:
You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop.
不能无条件使用setstate,在componentDidUpdate中设置state会导致无限循环。
我想说完全避免它们。
使用哪种方法?
如果您使用的是以前的版本,则 16.3 使用 componentWillReceiveProps
如果您使用的是 16.3 或更高版本,请使用 getDerivedStateFromProps
Here is an interesting conversation to read
根据评论更新:
应用条件时需要具体,this.state !== prevState` 是不够的。
假设您的 this.state.counter = 1 并且您正在将其更新为 componentDidUpdate
并将 this.state.counter 递增为 2。
这总是会导致无限循环。
关于javascript - 组件中的无限循环将更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471485/