用于获取项目的 React 设计模式

React design pattern for fetching items

我有许多 React 组件需要获取某些项目才能显示。这些组件可以是功能组件,除了非常简单的 componentDidMount 回调。是否有一个好的设计模式可以让我 return 功能组件?

class Things extends React.Component {

  componentDidMount() {
    this.props.fetchThings()
  }

  render() {
    things = this.props.things
    ...
  }
}

我正在使用 react-redux,我还使用 connect 将我的组件连接到我的 reducer 和操作。这是该文件:

import { connect } from 'react-redux'
import Things from './things'
import { fetchThings } from '../../actions/thing_actions'

const mapStateToProps = ({ things }) => ({
  things: things,
})

const mapDispatchToProps = () => ({
  fetchThings: () => fetchThings()
})

export default connect(mapStateToProps, mapDispatchToProps)(Things)

改为获取此文件中的内容是否有意义?也许是这样的:

import { connect } from 'react-redux'
import Things from './things'
import { fetchThings } from '../../actions/thing_actions'

const mapStateToProps = ({ things }) => ({
  things: things,
})

class ThingsContainer extends React.Component {
  componentDidMount() {
    fetchThings()
  }
  render() {
    return (
      <Things things={this.props.things} />
    )
  }
}

export default connect(mapStateToProps)(ThingsContainer)

功能组件是指不任何事情的组件。你只要给他们道具,他们就会渲染。事实上,如果您的组件需要获取任何内容,您的组件很可能应该转换为 container 来获取您需要的数据。然后,您可以将组件的 UI 部分抽象为一个或多个纯功能组件,您的容器通过传递它作为道具获得的数据来呈现这些组件。

我相信 presentational/container 组件拆分是您在这里寻找的模式。