我是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
吗? 文档中有什么我想念的吗?
要connect
的参数的名称为mapStateToProps
和mapDispatchToProps
。 它们通常被称为mapState
和mapDispatch
,但是您可以根据需要调用函数。
在此示例中, fungetStore
是“ mapState”函数的示例。 不管它被称为mapStateToProps
, mapState
, fungetStore
还是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()