首页 > 解决方案 > 如何将获取的结果作为路由器通量中组件的参数传递?

问题描述

我正在尝试使用路由器通量在标签栏的组件内传递参数以反应本机。我所做的是获取的结果作为参数在标签栏内的组件内传递。以下是我的代码

主页.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了。我的代码有什么错误,请帮忙。

标签: reactjsreact-nativejsxreact-native-router-flux

解决方案


所以第一次你的组件渲染,this.state.cats是未定义的。

你可以用你的代码做的是:

  1. 将您的 fetch 调用包装在异步调用中,即一个承诺。例如,

//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
  });
}

或者

  1. 对于您的组件<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>

PS专注于你的状态管理,你很高兴。


推荐阅读