[英]Why is React treating my array as if it were empty?
我目前正在使用MERN堆棧創建一個完整的堆棧應用程序,但遇到了一個以前沒有的問題。 當我使用.map()
函數遍歷數組時, 即使控制台記錄我的數組存在,長度為4並具有所有適當的元素(它們都是對象),我的數組也不會被遍歷通過.map()
函數。
我還注意到,當我控制台記錄array.length
,我得到的是零-盡管在上一個日志中,我被告知該數組的長度為4(應該是長度)。
以下是填充數組的位置:
getTournaments(){
fetch("http://localhost:3001/tournament", {
credentials: 'include',
method: "get",
headers: {
'Accept':'application/json',
'Content-Type': 'application/json',
}
})
.then( (response) => response.json())
.then( (response) => {
if(response){
response.map((tournament)=> {
this.state.tournaments.push(tournament);
})
}
})
}
我在這里調用getTournaments()
:
componentDidMount(){
this.getTournaments(); ...
這是我嘗試映射到數組的方式:
this.state.tournaments.map((tournament,index) => {
return (<div key={index}> {tournament.title} </div>);
})
最后,當我調用渲染函數時,會創建控制台日志。 這是render函數:
renderSpectatorView(){
var array = [1,2,3];
var currentTournaments = this.state.tournaments;
// console.log(currentTournaments);
return(
<div className="page-wrapper">
{/* BOOTSTRAP MODAL */}
{this.state.isAuth ? <Button onClick={this.goToCreate} bsStyle="primary">Create Tournament</Button> : null}
<div className="tournament-wrapper">
{
console.log(this.state.tournaments)}
{ console.log(this.state.tournaments.length)}
</div>
</div>
);
}
在項目的早期,我使用了幾乎完全相同的方法(但更為復雜,因為我遍歷了數組中每個對象的屬性),因此我對為什么這種方法不起作用感到困惑。 我最初的想法是,也許在我從API提取數據之前調用了render函數-但是這些值正確記錄了。
我應該使用promise還是async / await來實現這一點,以確保僅在數據收集之后才渲染? 感謝您提供的所有幫助。
問題是this.state.tournaments.push(tournament);
如果要觸發更新,則必須使用setState。 做類似的事情
.then( (response) => {
if(response){
this.setState({tournaments: [...this.state.tournaments, ...response.tournaments]});
}
})
蔓延是因為您似乎想在this.state.tournaments
中已擁有要保留的值,但我不確定。 如果僅設置一次,則可以簡單地執行
.then( (response) => {
if(response){
this.setState({tournaments: response.tournaments});
}
})
請參閱此處以獲取更多信息ReactJS文檔:不要直接修改狀態
簡而言之; 如果沒有setState
,您將永遠無法改變狀態;您不能做到這一點this.state.thing = X
,您不能做到這一點this.state.thing.push()
或其他任何方法。 修改state
的唯一方法是使用setState
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.