将变量放入render()返回-React Native [英] Putting a variable inside render() return - React Native

查看:218
本文介绍了将变量放入render()返回-React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mapping json数据,可以console.log我的结果,但是我无法在渲染器中插入这些值.

I am mapping json data and can console.log my result, but I can't insert those values in the render.

这是我的渲染代码:

data_use = responseJson;
     const result_id = data_use.map(function(val) {
      return val.id;
    }).join(',');
    console.log(result_id);
render(){
return(

     <View style = { styles.MainContainer }>
      <View>
       <Card>          
          <View>
          <Text>{result_id}</Text>
         </View>
       </Card>
       </View>
     </View>
   );
  }

我遇到的错误是ReferenceError: result_id is not defined.因为它已定义,这很奇怪吗?

The error that I am getting is ReferenceError: result_id is not defined. Which is odd because it is defined?

推荐答案

如果从服务器加载数据,此方法将很有用.

This approach will be useful if the data is loaded from a server.

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

}

componentDidMount() {
   // Your code to fetch data from server

   this.setState({ data: your_array_from_fetch });
}

render(){
   return(
     <View style={ styles.MainContainer }>
        <View>
           <Card>          
              <View>
                {
                   this.state.data.length > 0 ?
                       this.state.data.map((val, index) => {
                           return (
                              <Text key={index}>val.id</Text>
                           );
                       } ).join(',');
                    : null
                 }
              </View>
           </Card>
         </View>
      </View>
  );
}

我没有做出任何假设,我相信这就是您想要的!如果有任何问题,请在下面写下.

I made few assumption from my side and I believe this is what you want! If any issue write that down below.

    可以通过测试数据数组长度是否大于零来解决瑜伽节点问题.通常在渲染未返回任何内容时会发生这种情况.
  1. 我使用componentDidMount而不是componentWillMount,因为componentWillMount已过时.
  1. Yoganode issue can be fixed by testing if the data array length is greater than zero. This usually happens when render does not return anything.
  2. I used componentDidMount instead of componentWillMount because componentWillMount is deprecated.

尝试此条件渲染

{
    this.state.data.length > 0 ?
        this.state.data.map((val, index) => {
           if (some_var == another_var) {
              return (
                 <Text key={index}>val.id</Text>
              );
           }
        }).join(',');
    : null
}

这篇关于将变量放入render()返回-React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆