Initialize component with Async data

馋奶兔 提交于 2019-12-04 23:43:08

You should separate data components from presentation components (see post here).

So in your small example, MyDropdown should be passed all the data it needs in order to render the component. That would mean fetching the data in App (or some parent component of the component actually rendering the view.

Since you're working with React and Redux, the react-redux library provides a helper function to generate containers that fetch the data required for your presentation component.

To do that, change App to:

import { connect } from 'react-redux'
import MyDropdown from '../components/mydropdown';
import { loadData } from '../actions';

// This class is not exported
class App extends Component {
  componentDidMount() {
    this.props.loadData()
  }
  render() {
    return (
      <div className="page-content">
        <div className="option-bar">
          <MyDropdown data={this.props.data}/>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  const { data } = state
  return {
    data
  }
}

function mapDispatchToProps(dispatch) {
  return {
    loadData(){
      dispatch(loadData())
    }
  }
}

// Export a container that wraps App
export default connect(mapStateToProps, mapDispatchToProps)(App);

Alternatively, you could keep App the same and change MyDropdown to:

import { connect } from 'react-redux'
import { loadData } from '../actions';

// Exporting this allows using only the presentational component
export class MyDropdown extends Component {
  componentDidMount() {
    this.props.loadData()
  }
  render() {
    return(
      <select>
         {renderOptions(this.props.data)}
      </select>
    );
  }
}

function mapStateToProps(state) {
  const { data } = state
  return {
    data
  }
}

function mapDispatchToProps(dispatch) {
  return {
    loadData(){
      dispatch(loadData())
    }
  }
}

// By default, export the container that wraps the presentational component
export default connect(mapStateToProps, mapDispatchToProps)(MyDropdown);

In both cases, look at what is actually being exported as default at the end. It's not the component; it's the return of connect. That function wraps your presentational component and returns a container that is responsible for fetching the data and calling actions for the presentational component.

This gives you the separation you need and allows you to be flexible in how you use the presentation component. In either example, if you already have the data you need to render MyDropdown, you can just use the presentation component and skip the data fetch!

You can see a full example of this in the Redux docs here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!