与 REST 反应 API - 挂载状态或 GET?

React with REST API - State or GET on mount?

我们目前正在构建一个带有 REST API 后端的 React-Redux 前端,该后端由 Node.js 提供支持。我不确定在安装组件时是使用 Redux 还是简单调用 API。

该组件是一个简单的配置文件列表,将在整个网站(但不是一直)显示。

抱歉问这个问题。也许有一些东西可以通读?

我建议你看两件事:

1) Facebook 上的第一个 React 教程被低估了: https://facebook.github.io/react/docs/thinking-in-react.html

它提供了一种非常清晰的方式来思考如何思考视图的树结构。

2) 从那里开始阅读有关容器和组件的内容: https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

这个 post 解释了 React 组件经常做两件事:充当渲染器和控制器(在 MVC 上同时承担 V 和 C)。

现在,您的 React 视图需要的是一个控制器。每当您安装组件时获取它与两个不同的问题重叠:如何显示信息和如何获取信息。

您可以使用一个更大的 React 组件来管理您的应用程序的完整状态:

class MyApp extends React.Component {
  componentDidMount() {
    fetch('/profiles').then(res => res.json().then(::this.setState))
  }
  render() {
    if (this.state) {
      return <ProfileList profiles={this.state} />
    } else {
      return <span>Loading...</span>
    }
  }
}

那将是你的 "Container"。您的 "Component" 是配置文件列表的纯粹表示,不需要关心该信息是如何检索的:

class ProfileList extends React.Component {
  render() {
    return <ul>
      {
        this.props.profiles.map(
          profile => <li key={profile.id}>{profile.name}</li>
        )
      }
    </ul>
  }
}

Redux 只是实现此目的的另一种方式,它可以更好地重用信息,并使相同的信息可用于不同的组件(将 "store" 的实例隐藏为混合)。结构之上的 MyApp class 与 redux 中的 Provider class 具有相似的功能:允许子组件访问显示自身所需的信息。