我正在尝试使用路由器flux在反应原生的标签栏的组件内传递params。我所做的是获取的结果作为params在标签栏内的组件内传递。以下是我的代码
Home.js
fetch(GLOBAL.COURSES)
.then((response) => response.json())
.then((responseData) => {
this.setState({
cats: responseData.data,
vdo: responseData.video,
isLoading: false
})
})
..
...
<Tabs>
<Tab
heading="Courses"
>
<Courses cats={this.state.cats} />
</Tab>
...
...
</Tabs>
在Courses
页面中,我正试图将此道具作为
{this.props.cats.map(category =>
<View>
....
....
</View>
)}
我得到undefined is not an object evaluating this.props.cats.map
。我的代码中的错误请帮忙。
因此,第一次渲染组件时,this.state.cats
未定义。
你可以用你的代码做什么:
//function
const fetchCats = async () => {
const responseData = await fetch(GLOBAL.COURSES)
.then((response) => response.json())
.then((responseDataSuccess) => {
return responseDataSuccess;
});
this.setState({
cats: responseData.data,
vdo: responseData.video,
isLoading: false
});
}
要么
<Courses />
,你可以这样做,它不会渲染,直到汽车状态具有所需的价值,并且这是一个很好的做法初始化this.state = { cars: [] }
import { get } from 'lodash';
// a utility set for javascript
<Tabs>
<Tab heading="Courses" >
{get(this.state, cats) && <Courses cats={this.state.cats} />}
</Tab>
...
...
</Tabs>
附:专注于你的国家管理,你很高兴。
您试图在尚未收到服务响应的情况下遍历您的cat
阵列。
常见的模式是在等待服务响应时显示加载微调器。
<Tab heading="Courses">
{!this.state.isLoading && (<Courses cats={this.state.cats} />)}
{this.state.isLoading && "Loading..."}
</Tab>
因此在调用构造函数之后调用render方法。所以你有一个空数组。 this.props.cats将有一个空数组。并使用空数组呈现组件。然后使用数组数据调用setState,再次调用renders方法,那个时候this.props.cats将有一个数组的数据。嗯确保你有初始状态定义为
state = {
cats = []
....
}
or
this.state = {
cats = []
....
}
如果它返回一个数组,也做一个console.log responseData.data
。