Paw*_*ski -1 javascript setstate reactjs
我试图设置状态以响应Api onClick。状态获得更新,但是当我第一次单击时没有更新,第二次单击是的,它的确更新了。
fetch(URL)
.then(res => res.json())
.then(res => {
this.setState({
recipesList: res
});
});
console.log(this.state.recipesList);
};
Run Code Online (Sandbox Code Playgroud)
有人能帮我吗 ?
setState()是异步的。这意味着React会选择何时才是更新状态的正确时间,而这可能并非您正在执行的时间console.log()。
console.log()在setState回调函数上使用,因此当状态更改时,将执行您的函数:
fetch(URL)
.then(res => res.json())
.then(res => {
this.setState({
recipesList: res
},()=>{//setState callback.
console.log(this.state.recipesList);
});
});
Run Code Online (Sandbox Code Playgroud)
这是由于ReactJS生命周期。如果您在内部执行该函数componentWillMount,则不会导致第二次渲染:
class yourComponent extends React.Component{
state = {
recipesList: []
}
componentWillMount(){
fetch(URL)
.then(res => res.json())
.then(res => {
this.setState({
recipesList: res
},()=>{//setState callback.
console.log(this.state.recipesList);
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您
fetch在内部使用过componentWillMount(),则可以:
在渲染方法中,使用map函数,如下所示:
render(){
return (
<div className="App">
<div className="contentWrapper">
{
this.state.recipesList.map(item => {
return (
<div className="recispesList">
<h1>{item.title}</h1>
</div>
);
})
}
</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |