React 中数组返回未定义元素
我有一个类组件,它在
render()
之前进行异步调用,并将结果存储到其状态中。异步调用在渲染之前使用
componentWillMount()
调用,它使用
this.renderData()
。异步响应返回一个数组数组,但在这种情况下,我只对第一个数组感兴趣。所以我将结果
collections.first
存储到状态
arrayData
中。我可以成功地 console.log 状态
arrayData
,它显示 8 个元素(见屏幕截图)。但是,当我尝试使用
Array.at(index)
或
Array[index]
访问具有索引的元素时,我收到未定义的错误。
如何正确检索索引?总体目标是从结果中检索一个值并在渲染函数中显示图像
<img src={this.state.arrayData.at[2].url}> </img>
/ 但我不确定为什么会发生 Undefined。
这是我目前所得到的:
class Gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
arrayData: null,
};
}
renderData = async () => {
// async request code here which sets fetchURL and requestOptions
const collections = await fetch(fetchURL, requestOptions).then((data) =>
data.json()
);
if (collections ) {
this.setState({ arrayData: collections.first });
}
}
};
componentWillMount() {
this.renderData ();
}
render() {
console.log(this.state.arrayData); // correctly outputs array of length 8 (see output below)
console.log(this.state.arrayData[2]); // undefined error
console.log(this.state.arrayData.at(2); // undefined error
return(
// some render code
<img src={this.state.arrayData.at[2].url}> </img> // cant retrieve
);
}
}
当记录为
this.state.arrayData
时,响应中的数组输出显示 8 个项目正常
使用
console.log(this.state.arrayData[2]); 记录时的错误代码
react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of null (reading '2')
at Gallery.render (Gallery.jsx:61:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performSyncWorkOnRoot (react-dom.development.js:26096:1)
使用
console.log(this.state.arrayData.at(2)); 记录时的错误代码
Uncaught TypeError: Cannot read properties of null (reading 'at')
at Gallery.render (Gallery.jsx:61:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performSyncWorkOnRoot (react-dom.development.js:26096:1)
我会解释这里发生了什么:
第一次渲染组件时, this.state.arrayData 是 未定义 的,从服务器获取数据后,组件再次渲染,您可以在控制台中看到响应的结果,但是当您尝试访问索引 2 处的数组并且数据未定义时,您将收到此错误。
因此解决方案很简单,检查 this.state.arrayData 是否为真,然后显示组件,否则创建一个加载组件。
render() {
if (!this.state.arrayData) {
return <h1>...Loading</h1>
}
return(
// some render code
<img src={this.state.arrayData.at[2].url}> </img> // cant
retrieve
);
}