简体   繁体   English

React组件的数据存储

[英]Data storing of React Components

I am thinking of creating a list components which receive list of items and then return a list of <li></li> . 我正在考虑创建一个列表组件,该组件接收项目列表,然后返回<li></li> Moreover, the list can be appended dynamically via ajax call. 而且,该列表可以通过ajax调用动态附加。

I would like to ask in this situation, where should I store the data, props or state? 我想问在这种情况下,我应该在哪里存储数据,道具或状态?

In most cases: use state for data that changes over time. 在大多数情况下: 将状态用于随时间变化的数据。

A common way of doing this is to have two components, List and ListItem . 这样做的常见方法是具有两个组件, ListListItem The List component should handle the state, ajax calls and the transfer of list content as props to the child component ListItem . List组件应处理状态,ajax调用以及将列表内容作为道具传递给子组件ListItem

<List>
    <ListItem>
    <ListItem>
    <ListItem>
    ...
</List>

So List stores the data as state. 因此, List将数据存储为状态。 And ListItem is stateless and just receive its data from List . ListItem是无状态的,仅从List接收其数据。

React docs: What Components Should Have State? React docs:什么组件应该有状态?

Most of your components should simply take some data from props and render it. 您的大多数组件都应该简单地从props中获取一些数据并进行渲染。 However, sometimes you need to respond to user input, a server request or the passage of time. 但是,有时您需要响应用户输入, 服务器请求或时间的流逝。 For this you use state. 为此,请使用状态。

Try to keep as many of your components as possible stateless. 尝试使尽可能多的组件保持无状态。 By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application. 通过这样做,您可以将状态隔离到最逻辑的位置,并最大程度地减少冗余,从而使推理应用程序更加容易。

A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. 一种常见的模式是创建几个仅呈现数据的无状态组件,并在层次结构中的上方放置一个有状态组件,该状态组件通过道具将其状态传递给其子级。 The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way. 有状态组件封装了所有交互逻辑,而无状态组件负责以声明的方式呈现数据。

Maybe this helps to understand the structure of building react apps: Tutorial: Thinking in React 也许这有助于了解构建React应用程序的结构: 教程:React中的思考

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

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