简体   繁体   English

react-native 中的重复组件

[英]Repetitive component in react-native

I developed an api that returns some data for each user that uses my React Native app.我开发了一个 api,它为每个使用我的 React Native 应用程序的用户返回一些数据。 This API returns an array of objects which can I console.log() and see them.这个 API 返回一个对象数组,我可以在console.log()查看它们。

What I am trying to do is show each object in this array in a particular ( element)我想要做的是在特定(元素)中显示此数组中的每个对象

listeFinale is declared in the state as an empty array listeFinale在状态中被声明为一个empty array

liste is the array of objects that is returned by the API liste是 API 返回的对象数组

The code below is executed if the fetch was successful如果fetch成功则执行下面的代码

this.state.listeFinale = this.state.liste.map(n => (
    <Text key={n.Id}>
      {n.Nume}
      {n.Observatii}
    </Text>
    )
)

Then, in the render() method I have:然后,在render()方法中,我有:

 return (
  <View style={styles.container}>
    <Text>Lists for user id {this.state.userId}</Text>
    {this.state.listeFinale}
  </View>
);

Nothing is shown in the app, all I see is the text and the user ID.应用程序中没有显示任何内容,我看到的只是文本和用户 ID。 I am new to React Native and I could really use some advice from you guys.我是 React Native 的新手,我真的可以从你们那里得到一些建议。

Thank you in advance!先感谢您!

You can make the map loop inside the render method.您可以在渲染方法中制作地图循环。

To reassign the state after a fetch use setState() ( in case you are not using the useState() hook )要在获取后重新分配状态,请使用setState() (以防您不使用useState()挂钩)

So you will have something like所以你会有类似的东西

state = {
    liste = []
}

componentLifeCycle () {// in case you don't use hooks
    fetch().then((response) => { // or async await
     this.setState({liste : response})
    }
}
return (
  <View style={styles.container}>
    <Text>Lists for user id {this.state.userId}</Text>
    {this.state.liste.length > 0 && this.state.liste.map(n => (
        <Text key={n.Id}>
          {n.Nume}
          {n.Observatii}
        </Text>
    )}
  </View>
);

Also I would suggest you use english when defining variables and other names in your code for better readability.此外,我建议您在代码中定义变量和其他名称时使用english ,以提高可读性。 You never know who might end up debugging or working on your code.您永远不知道谁可能最终会调试或处理您的代码。

Another suggestion would be to use Redux to store your ' fetch ' data inside your app state.另一个建议是使用 Redux 将您的“获取”数据存储在您的应用程序状态中。 And get it from there instead of doing fetch inside the component.并从那里获取它,而不是在组件内部进行 fetch。 Components should just render data from state and not interact directly with the API.组件应该只呈现来自状态的数据,而不是直接与 API 交互。 Keep them clean and simple.保持它们干净和简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM