Putting a variable inside render() return - React Native

我只是一个虾纸丫 提交于 2019-12-13 03:50:43

问题


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

Here is the code I have for my 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>
   );
  }

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


回答1:


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.

EDIT:

  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.

Try this conditional render

{
    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
}



回答2:


Everything you did is correct but variable you declared outside render? How can it be accessed in render

render(){
//considering array of objects in "data_use" state
 const result_id = this.state.data_use.map(function(val) {
      return val.id;
    }).join(',');

return(

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


来源:https://stackoverflow.com/questions/50449877/putting-a-variable-inside-render-return-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!