mapStateToProps 和 mapDispatchToProps 中的 ownProps 参数有什么用?

What is the use of the ownProps arg in mapStateToProps and mapDispatchToProps?

我看到传递给 Redux 中的 connect 函数的 mapStateToPropsmapDispatchToProps 函数将 ownProps 作为第二个参数。

[mapStateToProps(state, [ownProps]): stateProps] (Function):

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function):

可选的 [ownprops] 参数有什么用?

我正在寻找一个额外的例子来说明问题,因为 the Redux docs

中已经有一个

如果指定了 ownProps 参数,react-redux 会将传递给组件的 props 传递给你的 connect 函数。因此,如果您使用这样的连接组件:

import ConnectedComponent from './containers/ConnectedComponent'

<ConnectedComponent
  value="example"
/>

mapStateToPropsmapDispatchToProps 函数中的 ownProps 将是一个对象:

{ value: 'example' }

并且您可以使用此对象来决定从这些函数中 return 的内容。


例如,在博客上 post 组件:

// BlogPost.js
export default function BlogPost (props) {
  return <div>
    <h2>{props.title}</h2>
    <p>{props.content}</p>
    <button onClick={props.editBlogPost}>Edit</button>
  </div>
}

你可以 return Redux action creators 做一些特定的事情 post:

// BlogPostContainer.js
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import BlogPost from './BlogPost.js'
import * as actions from './actions.js'

const mapStateToProps = (state, props) =>
  // Get blog post data from the store for this blog post ID.
  getBlogPostData(state, props.id)

const mapDispatchToProps = (dispatch, props) => bindActionCreators({
  // Pass the blog post ID to the action creator automatically, so
  // the wrapped blog post component can simply call `props.editBlogPost()`:
  editBlogPost: () => actions.editBlogPost(props.id)
}, dispatch)

const BlogPostContainer = connect(mapStateToProps, mapDispatchToProps)(BlogPost)
export default BlogPostContainer

现在你可以像这样使用这个组件:

import BlogPostContainer from './BlogPostContainer.js'

<BlogPostContainer id={1} />

goto-bus-stop 的回答很好,但要记住的是,根据 redux 的作者,Abramov/gaearon,在这些函数中使用 ownProps 会使它们变慢,因为它们必须重新绑定动作创建者当道具改变时。

在 link 中查看他的评论: https://github.com/reduxjs/redux-devtools/issues/250

ownProps指的是parent传下来的道具。 一个组件通常有 2 个输入源:商店和它的 parent 组件传递的任何道具。

因此,例如:

Parent.jsx:

...
<Child prop1={someValue} />
...

Child.jsx:

class Child extends Component {
  props: {
    prop1: string,
    prop2: string,
  };
...
}

const mapStateToProps = (state, ownProps) => {
  const prop1 = ownProps.prop1;
  const tmp = state.apiData[prop1]; // some process on the value of prop1
  return {
    prop2: tmp
  };
};

mapStateToPropsmapDisptachToProps 之间的区别在于它们各自对商店的处理方式。第一个用于 READ,后者用于 WRITE。

mapStateToProps 将存储值连接为 props mapDisptachToProps 是让您更新商店的函数。