![](/img/trans.png)
[英]ReactJS - Calling setState inside for loop, updating the state and displaying the result
[英]ReactJs : Setstate is not updating the state
下面是分配的初始 state
state = {
movie : null,
actors : null,
directors : [],
loading : false
}
下面是我设置的 state 集,最后将 state 设置为设置和未设置时的注释。 我无法在外面访问this.state
。
this.setState({movie:result},() => {
//then fetch the actors
const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
fetch(endpoint)
.then(result => result.json())
.then(result=>{
const directors =result.crew.filter((member)=> member.job==='Director' );
this.setState({
actors : result.cast,
directors,
loading : false
})
console.log(this.state); //here value is coming
})
})console.log(this.state); //here value is not coming
如何通过更新的信息获取this.state
值?
render() {
//removed code below mull div
return (
<div className="rmdb-movie">
{this.state.movie ?
<div>
<Navigation movie={this.props.location.movieName}/>
</div>
: null
}
</div>
)
}
您遇到的是使用异步函数的结果。 只要设置了 state,就会调用传递给this.setState()
的回调,并且在调用this.setState()
之间可能会有延迟。 这意味着当您到达第二个console.log()
时,可能会或可能不会执行回调。
这解释了为什么您会看到这些结果。 第一个console.log()
实际上是在第二个console.log
之后调用的。
这是反应生命周期。 setState function 不会立即执行。 内部的 console.log 打印出好的值,因为在 setState 的回调中你是 sur 它被执行了。 外部 console.log 在 setState 实际修改 state 之前执行,因此您看不到更新的信息。
您所看到的实际上是预期的,这是因为 Javascript 通常和您的特定 fetch API 调用是异步的。 您的第一个 console.log() 在 fetch 请求的响应中,因此它仅在服务器返回响应(可能是几秒钟或更长时间)时执行,然后设置 state,然后使用控制台打印。日志。 第二个 console.log 在外面,实际上会立即打印,甚至在异步 API 调用之前,在 state 实际更新之前。 因此,我建议您在设置 state 后要执行的任何操作都应在第一个 console.log 所在的位置执行。 或者最好像这样在回调中传递给 this.setState 以确保 state 已更新。
this.setState({movie:result},() => {
//then fetch the actors
const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
fetch(endpoint)
.then(result => result.json())
.then(result=>{
const directors =result.crew.filter((member)=> member.job==='Director' );
this.setState({
actors : result.cast,
directors,
loading : false
},()=>{
// API Call has returned and state has been updated
// Now access this.state
});
})
})
setState 操作是异步的,您可以在react 文档中了解更多信息。
你想解决什么问题? 可能你需要使用钩子componentDidUpdate或者在下一次渲染调用中使用这个值。
我认为您应该重新考虑代码,因为结果不可能以您放置的方式出现在电影中。 除非您以某种方式更新 API function 中的另一个 state 以获取电影。 因此,您可以以某种方式从某些 onclick 或 onchange 或其他东西中调用您必须绑定到 class this.fetch = this.fetch.bind(this) 的 fetch 。
fetch =() =>{
const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
fetch(endpoint)
.then(result => result.json())
.then(result=>{
const directors =result.crew.filter((member)=> member.job==='Director' );
this.setState({
actors : result.cast,
directors,
loading : false,
movies:result
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.