【问题标题】:Unable to render react-native Component after fetching data from firebase从 firebase 获取数据后无法呈现 react-native 组件
【发布时间】:2019-03-23 12:39:08
【问题描述】:

我能够从 Firebase API 获取数据。我能够将状态设置为收到的数据(我可以在控制台中看到)。但是当我无法渲染组件时(将道具作为获取的数据传递)。这是我的代码:

    class NewMeals extends Component {

      constructor(props){
        super(props);
        this.state= {
          data:''
        }
      }

      async componentDidMount(){
        try{
          const res = await fetch('https://frego-cb5b5.firebaseio.com/recipes.json?auth=api_key');
          if(!res.ok){
            throw Error(res.statusText);
          }
          const json = await res.json();
          this.setState({data:json});
        }catch(err){
          console.log(err);
        }
      }


      renderItems=()=>{

        const items = this.state.data;
        const arr = Object.values(items);

        arr.forEach(i=>{
          return <HomeMeals  name={i.title} time={i.time} serve={i.serve}/>

        })


      }

      render(){
        const {mainView, CardSection, heading, } = styles;

        return( 

            <View style={mainView}>

              <Text style={heading}>New Meals This Week</Text>

              <ScrollView contentContainerStyle ={CardSection} horizontal={true} showsHorizontalScrollIndicator={false}>

                {this.renderItems()}


              </ScrollView>
              </ View>


        );
      }
    }

我希望 HomeMeals 组件会在调用 renderItems() 函数时从获取的数据中一一呈现特定名称。但我什么也得不到。

有什么建议吗?

【问题讨论】:

    标签: firebase react-native firebase-realtime-database axios fetch


    【解决方案1】:

    这里有几点。

    1. 进行更多调试(日志)。
        const items = this.state.data;
        const arr = Object.values(items);
        console.log("items and arr", items, arr, this.state);
    

    您从上面的日志中看到了什么值?这应该会给你一个提示。

    1. 下面的这个 (renderItems) 不起作用,因为它不会返回要渲染的元素(或任何东西)(正如您尝试的那样):
        renderItems=()=>{
          arr.forEach(i=>{
             return <HomeMeals  name={i.title} time={i.time} serve={i.serve}/>
          })
          ...
    

    您想要的是从 renderItems 函数返回元素(元素数组),如下所示:

        renderItems=()=>{
          return arr.map(i=>{
             return <HomeMeals  name={i.title} time={i.time} serve={i.serve}/>
          })
          ...
    

    您会注意到两件事:(1) 我添加了 return 关键字来返回 arr.map 返回的任何内容。以及 (2) arr.map vs arr.forEach 的使用。尝试自己找出原因;为什么 arr.map 有效而 arr.forEach 无效

    【讨论】:

    • 谢谢!!有效。 forEach 实际上并没有返回任何东西。大错特错!
    猜你喜欢
    • 2018-11-07
    • 2017-07-22
    • 1970-01-01
    • 2021-09-22
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多