【发布时间】:2020-03-29 21:49:34
【问题描述】:
我从 react-native 开始。
我正在尝试创建一个 ImageGallery。 拥有此 Gallery 的步骤之一是使用 API 的结果在状态下启动数组。
- 我在名为“images”的状态上启动了一个 void 数组
- 我通过 console.log 调用 API -->,我看到的结果正确
- 我想设置我的数组“images”
- 我想读取我的数组“图像”
这是我的代码
import React from 'react';
import {
View,
Image,
FlatList
} from 'react-native';
export default class TestGallery extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
images: []
};
}
componentDidMount() {
fetch("*************************************")
.then(res => res.json())
.then(res => console.log(res))
.then((result) => {
this.setState({
images: result.images
});
},
(error) => {
this.setState({
error
});
}
)
}
render() {
console.log('Step 3 : RENDER')
console.log(this.state.images)
return (
<View style={{ height: 200, width: 200 }}>
<FlatList
data={this.state.images}
renderItem={({ item }) => (
<Image
style={{ height: 200, width: 200, backgroundColor: 'red' }}
source={this.state.images}
/>
)}
/>
</View>
)
}
}
控制台:
Step 3 : RENDER
Array []
Array [
"photo(3).jpg",
"photo(7).jpg",
"photo(2).jpg",
"photo(8).jpg",
"photo(14).jpg",
"photo(12).jpg",
"photo(6).jpg",
"photo(15).jpg",
"photo(10).jpg",
"photo(9).jpg",
"photo(5).jpg",
"photo(1).jpg",
"photo(11).jpg",
"photo(13).jpg",
"photo(4).jpg",
]
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'result.images')]
有人可以帮助我吗? 为什么我不能 setState 我的数组“Images”
【问题讨论】:
标签: react-native state setstate