【问题标题】:Proper use of react-redux connect正确使用 react-redux 连接
【发布时间】:2017-05-12 21:29:27
【问题描述】:

我是 react-redux 的新手,我正在阅读这里的文档 https://github.com/reactjs/react-redux/blob/master/docs/api.md
文档说 connect 定义为:

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

但后来我看到了这个示例代码

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

您可以在代码中看到fungetStore 是在connect 中发送的。但是为什么要这样使用connect呢?不认为您必须定义mapStateToProps 和/或mapDispatchToProps?。我遗漏了文档中的某些内容?

【问题讨论】:

标签: redux react-redux


【解决方案1】:

connect 的参数名称为mapStateToPropsmapDispatchToProps。它们通常被称为mapStatemapDispatch,但您可以随意调用您的函数。

在此示例中,fungetStore 是“mapState”函数的示例。不管它被称为mapStateToPropsmapStatefungetStore 还是fred,它都是一个接收state 作为参数并作为第一个参数传递给connect 的函数。

另外,connect 的每个参数都是可选的。所有这些都是有效的:

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()

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 2019-11-19
    • 2019-09-05
    • 2018-03-23
    • 2018-10-16
    • 2018-12-04
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多