React 组件的数据存储

Data storing of React Components

我正在考虑创建一个列表组件,它接收项目列表,然后 return <li></li> 列表。此外,列表可以通过 ajax 调用动态附加。

请问在这种情况下,数据、props 或 state 应该存储在哪里?

大多数情况下:对随时间变化的数据使用状态。

一种常见的方法是使用两个组件,ListListItemList 组件应该处理状态、ajax 调用以及将列表内容作为 props 传递给子组件 ListItem

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

因此 List 将数据存储为状态。 ListItem 是无状态的,只是从 List.

接收数据

React docs: What Components Should Have State?

Most of your components should simply take some data from props and render it. 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.

也许这有助于理解构建 React 应用程序的结构:Tutorial: Thinking in React