我使用异步操作从我自己的 API 获取数据,但有时 React 不会等待操作完成,因此我的状态对象返回 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();
}
什么是错误?
最佳答案
您从服务器获取的数据
似乎包含一些空值。
尝试在收到数据时将其打印出来,并尝试对其进行过滤:
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) });
};
关于javascript - React.js 异步操作 setState 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60923883/