[英]React.js async operation setState returns null
我使用異步操作從我自己的 API 獲取數據,但有時反應不等待操作完成,因此我的狀態對象返回 null 並導致 null 錯誤。
構造函數:
constructor(props) {
super(props);
this.openCase = this.openCase.bind(this);
this.state = {
reward: {},
skins: [],
caseImg: ""
};
this.fillCase = this.fillCase.bind(this);
}
我的獲取代碼:
fillCase = async () => {
const link = encodeURI("https://localhost:44390/api/getskins");
const response = await fetch(link);
const data = await response.json();
this.setState({ skins: data });
};
我在組件安裝之前調用 fillCase:
componentWillMount(){
this.fillCase();
}
什么是錯誤?
看起來您從服務器獲取的data
包含一些空值。
嘗試在接收數據時打印出來,也嘗試過濾它:
fillCase = async () => {
const link = encodeURI("https://localhost:44390/api/getskins");
const response = await fetch(link);
const data = await response.json();
console.log(data);
this.setState({ skins: data.filter(d => d) });
};
您需要檢查 skins 是否為空數組
{ this.state.skins.length && this.state.skins.map....}
這里有幾個問題:
首先,您不將 CWM 用於任何異步操作。 改用 CDM。
使您的 CDM 異步而不是 fillCase() 方法。
另一種方法是在這里使用鈎子。 將您的數據獲取邏輯放在 useEffect 掛鈎中。 如果您熟悉鈎子,這只是一種更簡潔、更靈活的方式來做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.