正确使用react-redux connect

Proper use of react-redux connect

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

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

但随后我看到此示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 (
         
             { data.text }
         
      );
   }
}

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

Content = connect(fungetStore)(Content)

export default Content

您可以在代码中看到在连接中发送了fungetStore。但是为什么以这种方式使用连接?不认为您必须定义mapStateToProps和/或mapDispatchToProps?。文档中有些东西我遗漏了吗?


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

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

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

1
2
3
4
5
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()