Proper use of react-redux connect

佐手、 提交于 2019-12-25 16:57:16

问题


I'm new in react-redux and I was reading the documentation here https://github.com/reactjs/react-redux/blob/master/docs/api.md
The documentation says that connect is defined as:

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

But then I see this example code

import React from 'react'
import { connect } from 'react-redux'
import { getData } from '../actions'

class Content extends React.Component {

   constructor(props) {
      super(props);
  }

   componentWillMount() {
      this.props.dispatch(getData())
   }

   render() {
      const { data } = this.props; //This data is the same returned for fungetStore

      return (
         <div>
            <h1> { data.text } </h1>
         </div>
      );
   }
}

const fungetStore = store => {
   return {
      data: store  //Return the content of the store
   }
}

Content = connect(fungetStore)(Content)

export default Content

You can see in the code that the fungetStore is sent in connect. But why connect is used in this way? It's not supposed that you must define mapStateToProps and/or mapDispatchToProps?. There is something in the documentation that I'm missing out?


回答1:


The names of the parameters to connect are mapStateToProps and mapDispatchToProps. They're frequently referred to as mapState and mapDispatch, but you can call your functions anything you want.

In this example, fungetStore is an example of a "mapState" function. It doesn't matter whether it's called mapStateToProps, mapState, fungetStore, or fred, it's a function that receives state as an argument and is being passed as the first parameter to connect.

Also, each of the parameters to connect are optional. All of these are valid:

connect(mapState, mapDispatch)(MyComponent) // use state and dispatch actions via functions
connect(mapState)(MyComponent)              // use state
connect(null, mapDispatch)(MyComponent)     // dispatch actions via functions
connect(null, null)(MyComponent)            // dispatch actions via dispatch()
connect()(MyComponent)                      // dispatch actions via dispatch()


来源:https://stackoverflow.com/questions/43946749/proper-use-of-react-redux-connect

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