正确使用react-redux connect

问题描述 投票:0回答:1

我是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中发送的。 但是为什么以这种方式使用连接? 不建议您必须定义mapStateToProps和/或mapDispatchToProps吗? 文档中有什么我想念的吗?

redux react-redux
1个回答
2
投票

connect的参数的名称为mapStateToPropsmapDispatchToProps 。 它们通常被称为mapStatemapDispatch ,但是您可以根据需要调用函数。

在此示例中, fungetStore是“ mapState”函数的示例。 不管它被称为mapStateToPropsmapStatefungetStore还是fred mapState fungetStore ,它是一个将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()
© www.soinside.com 2019 - 2024. All rights reserved.