在mapStateToProps和mapDispatchToProps中使用ownProps arg有什么用?

the*_*ode 82 redux react-redux

我看到传递给Redux函数的函数mapStateToPropsmapDispatchToProps函数作为第二个参数.connectownProps

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

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function):
Run Code Online (Sandbox Code Playgroud)

什么是可选[ownprops]参数?

我正在寻找另一个例子来说明问题,因为Redux文档中已有一个例子

got*_*top 102

如果ownProps指定了参数,react-redux会将传递给组件的props传递给您的connect函数.所以,如果你使用这样的连通组件:

import ConnectedComponent from './containers/ConnectedComponent'

<ConnectedComponent
  value="example"
/>
Run Code Online (Sandbox Code Playgroud)

ownProps您的内部mapStateToPropsmapDispatchToProps功能将是一个对象:

{ value: 'example' }
Run Code Online (Sandbox Code Playgroud)

您可以使用此对象来决定从这些函数返回的内容.


例如,在博客文章组件上:

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

您可以返回对该特定帖子执行某些操作的Redux操作创建者:

// 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
Run Code Online (Sandbox Code Playgroud)

现在您将使用此组件,如下所示:

import BlogPostContainer from './BlogPostContainer.js'

<BlogPostContainer id={1} />
Run Code Online (Sandbox Code Playgroud)

  • 注意 - defaultProps中不包含defaultProps (10认同)

Bar*_*ing 11

ownProps是指父级传递的道具.

所以,例如:

Parent.jsx:

...
<Child prop1={someValue} />
...
Run Code Online (Sandbox Code Playgroud)

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
  };
};
Run Code Online (Sandbox Code Playgroud)


Ste*_*son 7

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

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