React native 数组在setState和API结果之后取消定义
我在乞求你的帮助 我正在尝试创建一个ImageGallery。 拥有此库的一个步骤是使用API的结果启动处于状态的数组React native 数组在setState和API结果之后取消定义,react-native,state,setstate,React Native,State,Setstate,我在乞求你的帮助 我正在尝试创建一个ImageGallery。 拥有此库的一个步骤是使用API的结果启动处于状态的数组 我在名为“images”的状态上启动一个空数组 我通过console.log调用API-->时,看到的结果是正确的 我想设置数组“图像”的状态 我想读取我的数组“图像” 这是我的密码 import React from 'react'; import { View, Image, FlatList } from 'react-native'; expo
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>
)
}
}
有人能帮我吗?
为什么我不能设置数组“图像”的状态
images
键的对象。那么,您必须为此调整API端点。要将结果数组置于您的状态,可以执行以下操作require
,并提供正确的图像路径。但是我非常确定您希望从uri
进行渲染,因此您必须使用uri
作为图像源,并提供正确的图像URLrenderItem
函数中的项来显示图像源,因为这是this.state.images
的一项。将保存在this.state.images
中的整个数组传递给图像源
images
键的对象。那么,您必须为此调整API端点。要将结果数组置于您的状态,可以执行以下操作require
,并提供正确的图像路径。但是我非常确定您希望从uri
进行渲染,因此您必须使用uri
作为图像源,并提供正确的图像URLrenderItem
函数中的项来显示图像源,因为这是this.state.images
的一项。将保存在this.state.images
中的整个数组传递给图像源
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')]
fetch(...)
.then(res => res.json())
.then(json => {
console.log(json)
this.setState({images: json})
})