Skip to main content

connect()

提示

connect 仍然有效,并且在 React-Redux 8.x 中受支持。然而,我们建议使用 hooks API 作为默认值.

¥connect still works and is supported in React-Redux 8.x. However, we recommend using the hooks API as the default.

概述

¥Overview

connect() 函数将 React 组件连接到 Redux 存储。

¥The connect() function connects a React component to a Redux store.

它向其连接的组件提供它需要从存储中获取的数据片段,以及可用于将操作分派到存储的函数。

¥It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

它不会修改传递给它的组件类;相反,它返回一个新的连接组件类,该类封装你传入的组件。

¥It does not modify the component class passed to it; instead, it returns a new, connected component class that wraps the component you passed in.

function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)

mapStateToPropsmapDispatchToProps 分别处理 Redux 存储的 statedispatchstatedispatch 将作为第一个参数提供给 mapStateToPropsmapDispatchToProps 函数。

¥The mapStateToProps and mapDispatchToProps deals with your Redux store’s state and dispatch, respectively. state and dispatch will be supplied to your mapStateToProps or mapDispatchToProps functions as the first argument.

mapStateToPropsmapDispatchToProps 的返回在内部分别称为 statePropsdispatchProps。如果已定义,它们将作为第一个和第二个参数提供给 mergeProps,其中第三个参数为 ownProps。然后,组合结果(通常称为 mergedProps)将提供给你连接的组件。

¥The returns of mapStateToProps and mapDispatchToProps are referred to internally as stateProps and dispatchProps, respectively. They will be supplied to mergeProps, if defined, as the first and the second argument, where the third argument will be ownProps. The combined result, commonly referred to as mergedProps, will then be supplied to your connected component.

connect() 参数

¥connect() Parameters

connect 接受四个不同的参数,全部是可选的。按照惯例,它们被称为:

¥connect accepts four different parameters, all optional. By convention, they are called:

  1. mapStateToProps?: Function
  2. mapDispatchToProps?: Function | Object
  3. mergeProps?: Function
  4. options?: Object

mapStateToProps?: (state, ownProps?) => Object

如果指定了 mapStateToProps 函数,新的封装器组件将订阅 Redux 存储更新。这意味着每当存储更新时,都会调用 mapStateToPropsmapStateToProps 的结果必须是一个普通对象,它将被合并到封装组件的 props 中。如果你不想订阅存储更新,请传递 nullundefined 代替 mapStateToProps

¥If a mapStateToProps function is specified, the new wrapper component will subscribe to Redux store updates. This means that any time the store is updated, mapStateToProps will be called. The results of mapStateToProps must be a plain object, which will be merged into the wrapped component’s props. If you don't want to subscribe to store updates, pass null or undefined in place of mapStateToProps.

参数

¥Parameters

  1. state: Object
  2. ownProps?: Object

mapStateToProps 函数最多采用两个参数。声明的函数参数的数量(也称为数量)会影响函数的调用时间。这也决定了该函数是否会接收 ownProps。参见注释 此处

¥A mapStateToProps function takes a maximum of two parameters. The number of declared function parameters (a.k.a. arity) affects when it will be called. This also determines whether the function will receive ownProps. See notes here.

state

如果你的 mapStateToProps 函数被声明为采用一个参数,则只要存储状态发生变化,就会调用该函数,并将存储状态作为唯一参数。

¥If your mapStateToProps function is declared as taking one parameter, it will be called whenever the store state changes, and given the store state as the only parameter.

const mapStateToProps = (state) => ({ todos: state.todos })
ownProps

如果你的 mapStateToProps 函数被声明为采用两个参数,则每当存储状态更改或封装器组件接收新的 props(基于浅层相等比较)时,都会调用该函数。它将存储状态作为第一个参数,封装器组件的 props 作为第二个参数。

¥If your mapStateToProps function is declared as taking two parameters, it will be called whenever the store state changes or when the wrapper component receives new props (based on shallow equality comparisons). It will be given the store state as the first parameter, and the wrapper component's props as the second parameter.

按照惯例,第二个参数通常称为 ownProps

¥The second parameter is normally referred to as ownProps by convention.

const mapStateToProps = (state, ownProps) => ({
todo: state.todos[ownProps.id],
})

返回

¥Returns

你的 mapStateToProps 函数应返回一个对象。该对象通常称为 stateProps,将作为 props 合并到你连接的组件中。如果定义 mergeProps,它将作为第一个参数提供给 mergeProps

¥Your mapStateToProps functions are expected to return an object. This object, normally referred to as stateProps, will be merged as props to your connected component. If you define mergeProps, it will be supplied as the first parameter to mergeProps.

mapStateToProps 的返回决定了连接组件是否会重新渲染(详情 此处)。

¥The return of the mapStateToProps determine whether the connected component will re-render (details here).

mapStateToProps 的推荐使用方法请参考 我们的 mapStateToProps 使用指南

¥For more details on recommended usage of mapStateToProps, please refer to our guide on using mapStateToProps.

你可以将 mapStateToPropsmapDispatchToProps 定义为工厂函数,即返回一个函数而不是一个对象。在这种情况下,你的返回函数将被视为真正的 mapStateToPropsmapDispatchToProps,并在后续调用中被调用。你可能会看到有关 工厂职能 的注释或我们的性能优化指南。

¥You may define mapStateToProps and mapDispatchToProps as a factory function, i.e., you return a function instead of an object. In this case your returned function will be treated as the real mapStateToProps or mapDispatchToProps, and be called in subsequent calls. You may see notes on Factory Functions or our guide on performance optimizations.

mapDispatchToProps?: Object | (dispatch, ownProps?) => Object

通常称为 mapDispatchToPropsconnect() 的第二个参数可以是对象、函数,也可以不提供。

¥Conventionally called mapDispatchToProps, this second parameter to connect() may either be an object, a function, or not supplied.

默认情况下,你的组件将接收 dispatch,即,当你不向 connect() 提供第二个参数时:

¥Your component will receive dispatch by default, i.e., when you do not supply a second parameter to connect():

// do not pass `mapDispatchToProps`
connect()(MyComponent)
connect(mapState)(MyComponent)
connect(mapState, null, mergeProps, options)(MyComponent)

如果将 mapDispatchToProps 定义为函数,则将使用最多两个参数来调用它。

¥If you define a mapDispatchToProps as a function, it will be called with a maximum of two parameters.

参数

¥Parameters

  1. dispatch: Function
  2. ownProps?: Object
dispatch

如果你的 mapDispatchToProps 被声明为一个带有一个参数的函数,它将被赋予你的 storedispatch

¥If your mapDispatchToProps is declared as a function taking one parameter, it will be given the dispatch of your store.

const mapDispatchToProps = (dispatch) => {
return {
// dispatching plain actions
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
reset: () => dispatch({ type: 'RESET' }),
}
}
ownProps

如果你的 mapDispatchToProps 函数被声明为采用两个参数,则它将以 dispatch 作为第一个参数和传递给封装器组件的 props 作为第二个参数来调用,并且每当连接的组件收到新的 props 时就会重新调用。

¥If your mapDispatchToProps function is declared as taking two parameters, it will be called with dispatch as the first parameter and the props passed to the wrapper component as the second parameter, and will be re-invoked whenever the connected component receives new props.

按照惯例,第二个参数通常称为 ownProps

¥The second parameter is normally referred to as ownProps by convention.

// binds on component re-rendering
<button onClick={() => this.props.toggleTodo(this.props.todoId)} />

// binds on `props` change
const mapDispatchToProps = (dispatch, ownProps) => ({
toggleTodo: () => dispatch(toggleTodo(ownProps.todoId)),
})

mapDispatchToProps 声明的函数参数的数量决定了它们是否接收 ownProps。参见注释 此处

¥The number of declared function parameters of mapDispatchToProps determines whether they receive ownProps. See notes here.

返回

¥Returns

你的 mapDispatchToProps 函数应返回一个对象。对象的每个字段都应该是一个函数,调用该函数预计会向存储分派一个操作。

¥Your mapDispatchToProps functions are expected to return an object. Each fields of the object should be a function, calling which is expected to dispatch an action to the store.

mapDispatchToProps 函数的返回被视为 dispatchProps。它将作为属性合并到你连接的组件中。如果定义 mergeProps,它将作为第二个参数提供给 mergeProps

¥The return of your mapDispatchToProps functions are regarded as dispatchProps. It will be merged as props to your connected component. If you define mergeProps, it will be supplied as the second parameter to mergeProps.

const createMyAction = () => ({ type: 'MY_ACTION' })
const mapDispatchToProps = (dispatch, ownProps) => {
const boundActions = bindActionCreators({ createMyAction }, dispatch)
return {
dispatchPlainObject: () => dispatch({ type: 'MY_ACTION' }),
dispatchActionCreatedByActionCreator: () => dispatch(createMyAction()),
...boundActions,
// you may return dispatch here
dispatch,
}
}

更多推荐使用方法请参考 我们的 mapDispatchToProps 使用指南

¥For more details on recommended usage, please refer to our guide on using mapDispatchToProps.

你可以将 mapStateToPropsmapDispatchToProps 定义为工厂函数,即返回一个函数而不是一个对象。在这种情况下,你的返回函数将被视为真正的 mapStateToPropsmapDispatchToProps,并在后续调用中被调用。你可能会看到有关 工厂职能 的注释或我们的性能优化指南。

¥You may define mapStateToProps and mapDispatchToProps as a factory function, i.e., you return a function instead of an object. In this case your returned function will be treated as the real mapStateToProps or mapDispatchToProps, and be called in subsequent calls. You may see notes on Factory Functions or our guide on performance optimizations.

对象速记形式

¥Object Shorthand Form

mapDispatchToProps 可以是一个对象,其中每个字段都是 动作创造者

¥mapDispatchToProps may be an object where each field is an action creator.

import { addTodo, deleteTodo, toggleTodo } from './actionCreators'

const mapDispatchToProps = {
addTodo,
deleteTodo,
toggleTodo,
}

export default connect(null, mapDispatchToProps)(TodoApp)

在这种情况下,React-Redux 使用 bindActionCreators 将存储的 dispatch 绑定到每个操作创建者。结果将被视为 dispatchProps,它将直接合并到连接的组件,或作为第二个参数提供给 mergeProps

¥In this case, React-Redux binds the dispatch of your store to each of the action creators using bindActionCreators. The result will be regarded as dispatchProps, which will be either directly merged to your connected components, or supplied to mergeProps as the second argument.

// internally, React-Redux calls bindActionCreators
// to bind the action creators to the dispatch of your store
bindActionCreators(mapDispatchToProps, dispatch)

我们的 mapDispatchToProps 指南中还有一节介绍对象简写形式 此处 的使用。

¥We also have a section in our mapDispatchToProps guide on the usage of object shorthand form here.

mergeProps?: (stateProps, dispatchProps, ownProps) => Object

如果指定,则定义如何确定你自己的封装组件的最终 props。如果你不提供 mergeProps,则你的封装组件默认会收到 { ...ownProps, ...stateProps, ...dispatchProps }

¥If specified, defines how the final props for your own wrapped component are determined. If you do not provide mergeProps, your wrapped component receives { ...ownProps, ...stateProps, ...dispatchProps } by default.

参数

¥Parameters

mergeProps 最多应指定三个参数。它们分别是 mapStateToProps()mapDispatchToProps() 和封装器组件的 props 的结果:

¥mergeProps should be specified with maximum of three parameters. They are the result of mapStateToProps(), mapDispatchToProps(), and the wrapper component's props, respectively:

  1. stateProps
  2. dispatchProps
  3. ownProps

从它返回的普通对象中的字段将用作封装组件的属性。你可以指定此函数来根据 props 选择状态的一部分,或者将动作创建者绑定到 props 中的特定变量。

¥The fields in the plain object you return from it will be used as the props for the wrapped component. You may specify this function to select a slice of the state based on props, or to bind action creators to a particular variable from props.

返回

¥Returns

mergeProps 的返回值称为 mergedProps,这些字段将用作封装组件的 props。

¥The return value of mergeProps is referred to as mergedProps and the fields will be used as the props for the wrapped component.

注意:在 mergeProps 中创建新值将导致重新渲染。建议你记住字段以避免不必要的重新渲染。

¥Note: Creating new values in mergeProps will cause re-renders. It is recommended that you memoize fields in order to avoid unnecessary re-renders.

options?: Object

{
context?: Object,
areStatesEqual?: Function,
areOwnPropsEqual?: Function,
areStatePropsEqual?: Function,
areMergedPropsEqual?: Function,
forwardRef?: boolean,
}

context: Object

注意:仅在 >= v6.0 中支持此参数

¥Note: This parameter is supported in >= v6.0 only

React-Redux v6 允许你提供供 React-Redux 使用的自定义上下文实例。你需要将上下文实例传递给 <Provider /> 和连接的组件。你可以通过将上下文作为选项字段传递到此处,或作为渲染中的连接组件的 prop 将上下文传递到连接的组件。

¥React-Redux v6 allows you to supply a custom context instance to be used by React-Redux. You need to pass the instance of your context to both <Provider /> and your connected component. You may pass the context to your connected component either by passing it here as a field of option, or as a prop to your connected component in rendering.

// const MyContext = React.createContext();
connect(mapStateToProps, mapDispatchToProps, null, { context: MyContext })(
MyComponent,
)

areStatesEqual: (next: Object, prev: Object, nextOwnProps: Object, prevOwnProps: Object) => boolean

  • 默认值:strictEqual: (next, prev) => prev === next

    ¥default value: strictEqual: (next, prev) => prev === next

将传入的存储状态与其先前的值进行比较。

¥Compares incoming store state to its previous value.

const areStatesEqual = (next, prev) =>
prev.entities.todos === next.entities.todos

如果你的 mapStateToProps 函数计算量大且只涉及状态的一小部分,你可能希望覆盖 areStatesEqual。上面的示例将有效地忽略除该状态片段之外的所有内容的状态更改。此外,areStatesEqual 提供 nextOwnPropsprevOwnProps,以便在需要时更有效地确定连接组件感兴趣的状态范围。

¥You may wish to override areStatesEqual if your mapStateToProps function is computationally expensive and is also only concerned with a small slice of your state. The example above will effectively ignore state changes for everything but that slice of state. Additionally, areStatesEqual provides nextOwnProps and prevOwnProps to allow for more effective scoping of your state which your connected component is interested in, if needed.

这可能也会影响其他相等性检查,具体取决于你的 mapStateToProps 函数。

¥This would likely impact the other equality checks as well, depending on your mapStateToProps function.

areOwnPropsEqual: (next: Object, prev: Object) => boolean

  • 默认值:shallowEqual: (objA, objB) => boolean(当对象的每个字段相等时返回 true

    ¥default value: shallowEqual: (objA, objB) => boolean ( returns true when each field of the objects is equal )

将传入的 props 与其之前的值进行比较。

¥Compares incoming props to its previous value.

你可能希望覆盖 areOwnPropsEqual 作为将传入 props 列入白名单的方法。你还必须实现 mapStateToPropsmapDispatchToPropsmergeProps 来将 props 列入白名单。(通过其他方式实现这一点可能更简单,例如使用 重组的 mapProps。)

¥You may wish to override areOwnPropsEqual as a way to whitelist incoming props. You'd also have to implement mapStateToProps, mapDispatchToProps and mergeProps to also whitelist props. (It may be simpler to achieve this other ways, for example by using recompose's mapProps.)

areStatePropsEqual: (next: Object, prev: Object) => boolean

  • 类型:function

    ¥type: function

  • 默认值:shallowEqual

    ¥default value: shallowEqual

mapStateToProps 的结果与其先前的值进行比较。

¥Compares the result of mapStateToProps to its previous value.

areMergedPropsEqual: (next: Object, prev: Object) => boolean

  • 默认值:shallowEqual

    ¥default value: shallowEqual

mergeProps 的结果与其先前的值进行比较。

¥Compares the result of mergeProps to its previous value.

如果你的 mapStateToProps 使用记忆选择器,该选择器仅在相关 prop 发生更改时才返回新对象,你可能希望覆盖 areStatePropsEqual 以使用 strictEqual。这将是一个非常轻微的性能改进,因为可以避免每次调用 mapStateToProps 时对各个 props 进行额外的相等检查。

¥You may wish to override areStatePropsEqual to use strictEqual if your mapStateToProps uses a memoized selector that will only return a new object if a relevant prop has changed. This would be a very slight performance improvement, since would avoid extra equality checks on individual props each time mapStateToProps is called.

如果你的选择器产生复杂的 props,你可能希望覆盖 areMergedPropsEqual 以实现 deepEqual。例如:嵌套对象、新数组等(深度相等检查可能比仅仅重新渲染更快。)

¥You may wish to override areMergedPropsEqual to implement a deepEqual if your selectors produce complex props. ex: nested objects, new arrays, etc. (The deep equal check may be faster than just re-rendering.)

forwardRef: boolean

注意:仅在 >= v6.0 中支持此参数

¥Note: This parameter is supported in >= v6.0 only

如果 {forwardRef : true} 已传递给 connect,则向连接的封装组件添加引用实际上将返回封装组件的实例。

¥If {forwardRef : true} has been passed to connect, adding a ref to the connected wrapper component will actually return the instance of the wrapped component.

connect() 返回

¥connect() Returns

connect() 的返回是一个封装函数,它接受你的组件并返回一个封装组件及其注入的附加属性。

¥The return of connect() is a wrapper function that takes your component and returns a wrapper component with the additional props it injects.

import { login, logout } from './actionCreators'

const mapState = (state) => state.user
const mapDispatch = { login, logout }

// first call: returns a hoc that you can use to wrap any component
const connectUser = connect(mapState, mapDispatch)

// second call: returns the wrapper component with mergedProps
// you may use the hoc to enable different components to get the same behavior
const ConnectedUserLogin = connectUser(Login)
const ConnectedUserProfile = connectUser(Profile)

在大多数情况下,封装函数将立即被调用,而不保存在临时变量中:

¥In most cases, the wrapper function will be called right away, without being saved in a temporary variable:

import { login, logout } from './actionCreators'

const mapState = (state) => state.user
const mapDispatch = { login, logout }

// call connect to generate the wrapper function, and immediately call
// the wrapper function to generate the final wrapper component.

export default connect(mapState, mapDispatch)(Login)

用法示例

¥Example Usage

由于 connect 非常灵活,因此查看一些有关如何调用它的其他示例可能会有所帮助:

¥Because connect is so flexible, it may help to see some additional examples of how it can be called:

  • 仅注入 dispatch 并且不听存储

    ¥Inject just dispatch and don't listen to store

export default connect()(TodoApp)
  • 注入所有动作创建者(addTodocompleteTodo,...),无需订阅存储

    ¥Inject all action creators (addTodo, completeTodo, ...) without subscribing to the store

import * as actionCreators from './actionCreators'

export default connect(null, actionCreators)(TodoApp)
  • 注入 dispatch 和全局状态中的每个字段

    ¥Inject dispatch and every field in the global state

不要这样做!它会杀死任何性能优化,因为 TodoApp 将在每次状态更改后重新渲染。最好在视图层次结构中的多个组件上使用更细粒度的 connect(),每个组件仅监听状态的相关部分。

¥Don’t do this! It kills any performance optimizations because TodoApp will rerender after every state change. It’s better to have more granular connect() on several components in your view hierarchy that each only listen to a relevant slice of the state.

// don't do this!
export default connect((state) => state)(TodoApp)
  • 注入 dispatchtodos

    ¥Inject dispatch and todos

function mapStateToProps(state) {
return { todos: state.todos }
}

export default connect(mapStateToProps)(TodoApp)
  • 注入 todos 和所有动作创建者

    ¥Inject todos and all action creators

import * as actionCreators from './actionCreators'

function mapStateToProps(state) {
return { todos: state.todos }
}

export default connect(mapStateToProps, actionCreators)(TodoApp)
  • todos 和所有动作创建者(addTodocompleteTodo...)注入为 actions

    ¥Inject todos and all action creators (addTodo, completeTodo, ...) as actions

import * as actionCreators from './actionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actionCreators, dispatch) }
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • 注入 todos 和特定的动作创建者 (addTodo)

    ¥Inject todos and a specific action creator (addTodo)

import { addTodo } from './actionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({ addTodo }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • 使用简写语法注入 todos 和特定动作创建者(addTododeleteTodo

    ¥Inject todos and specific action creators (addTodo and deleteTodo) with shorthand syntax

import { addTodo, deleteTodo } from './actionCreators'

function mapStateToProps(state) {
return { todos: state.todos }
}

const mapDispatchToProps = {
addTodo,
deleteTodo,
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • todostodoActionCreators 作为 todoActions 注入,将 counterActionCreators 作为 counterActions 注入

    ¥Inject todos, todoActionCreators as todoActions, and counterActionCreators as counterActions

import * as todoActionCreators from './todoActionCreators'
import * as counterActionCreators from './counterActionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
return {
todoActions: bindActionCreators(todoActionCreators, dispatch),
counterActions: bindActionCreators(counterActionCreators, dispatch),
}
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • todos、todoActionCreators 和 counterActionCreators 一起注入为 actions

    ¥Inject todos, and todoActionCreators and counterActionCreators together as actions

import * as todoActionCreators from './todoActionCreators'
import * as counterActionCreators from './counterActionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(
{ ...todoActionCreators, ...counterActionCreators },
dispatch,
),
}
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • 直接注入 todos,以及所有 todoActionCreatorscounterActionCreators 作为 props

    ¥Inject todos, and all todoActionCreators and counterActionCreators directly as props

import * as todoActionCreators from './todoActionCreators'
import * as counterActionCreators from './counterActionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
return bindActionCreators(
{ ...todoActionCreators, ...counterActionCreators },
dispatch,
)
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • 根据 props 注入特定用户的 todos

    ¥Inject todos of a specific user depending on props

import * as actionCreators from './actionCreators'

function mapStateToProps(state, ownProps) {
return { todos: state.todos[ownProps.userId] }
}

export default connect(mapStateToProps)(TodoApp)
  • 根据 props 注入特定用户的 todos,将 props.userId 注入到 action 中

    ¥Inject todos of a specific user depending on props, and inject props.userId into the action

import * as actionCreators from './actionCreators'

function mapStateToProps(state) {
return { todos: state.todos }
}

function mergeProps(stateProps, dispatchProps, ownProps) {
return Object.assign({}, ownProps, {
todos: stateProps.todos[ownProps.userId],
addTodo: (text) => dispatchProps.addTodo(ownProps.userId, text),
})
}

export default connect(mapStateToProps, actionCreators, mergeProps)(TodoApp)

注意

¥Notes

mapToProps 函数的数量

¥The Arity of mapToProps Functions

mapStateToPropsmapDispatchToProps 声明的函数参数个数决定是否接收 ownProps

¥The number of declared function parameters of mapStateToProps and mapDispatchToProps determines whether they receive ownProps

注意:如果函数的正式定义包含一个强制参数(函数长度为 1),则 ownProps 不会传递给 mapStateToPropsmapDispatchToProps。例如,如下定义的函数不会接收 ownProps 作为第二个参数。如果 ownProps 的传入值为 undefined,则将使用默认参数值。

¥Note: ownProps is not passed to mapStateToProps and mapDispatchToProps if the formal definition of the function contains one mandatory parameter (function has length 1). For example, functions defined like below won't receive ownProps as the second argument. If the incoming value of ownProps is undefined, the default argument value will be used.

function mapStateToProps(state) {
console.log(state) // state
console.log(arguments[1]) // undefined
}

const mapStateToProps = (state, ownProps = {}) => {
console.log(state) // state
console.log(ownProps) // {}
}

没有强制参数或两个参数*的函数将收到 ownProps

¥Functions with no mandatory parameters or two parameters*will receive ownProps.

const mapStateToProps = (state, ownProps) => {
console.log(state) // state
console.log(ownProps) // ownProps
}

function mapStateToProps() {
console.log(arguments[0]) // state
console.log(arguments[1]) // ownProps
}

const mapStateToProps = (...args) => {
console.log(args[0]) // state
console.log(args[1]) // ownProps
}

工厂职能

¥Factory Functions

如果你的 mapStateToPropsmapDispatchToProps 函数返回一个函数,则它们将在组件实例化时被调用一次,并且它们的返回将在后续调用中分别用作实际的 mapStateToPropsmapDispatchToProps 函数。

¥If your mapStateToProps or mapDispatchToProps functions return a function, they will be called once when the component instantiates, and their returns will be used as the actual mapStateToProps, mapDispatchToProps, functions respectively, in their subsequent calls.

工厂函数通常与记忆选择器一起使用。这使你能够在闭包内创建特定于组件实例的选择器:

¥The factory functions are commonly used with memoized selectors. This gives you the ability to create component-instance-specific selectors inside the closure:

const makeUniqueSelectorInstance = () =>
createSelector([selectItems, selectItemId], (items, itemId) => items[itemId])
const makeMapState = (state) => {
const selectItemForThisComponent = makeUniqueSelectorInstance()
return function realMapState(state, ownProps) {
const item = selectItemForThisComponent(state, ownProps.itemId)
return { item }
}
}
export default connect(makeMapState)(SomeComponent)

旧版本文档

¥Legacy Version Docs

虽然 connect API 在我们所有主要版本之间几乎完全保持 API 兼容,但不同版本的选项和行为存在一些细微的变化。

¥While the connect API has stayed almost entirely API-compatible between all of our major versions, there have been some small changes in options and behavior from version to version.

有关旧版 5.x 和 6.x 版本的详细信息,请参阅 React Redux 存储库中的这些存档文件:

¥For details on the legacy 5.x and 6.x versions, please see these archived files in the React Redux repo: