mapStateToProps和mapDispatchToProps中ownProps arg的用途是什么?

将代码:

我看到在Redux 中传递给函数mapStateToPropsand mapDispatchToProps函数作为第二个参数。connectownProps

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

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

可选[ownprops]参数是什么?

我正在寻找一个其他示例来使事情变得清晰,因为Redux文档中已经有一个

前往公交车站:

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

import ConnectedComponent from './containers/ConnectedComponent'

<ConnectedComponent
  value="example"
/>

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

{ value: 'example' }

您可以使用该对象来决定从这些函数返回什么。


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

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

您可以返回对该特定帖子有所作为的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

现在,您将像这样使用此组件:

import BlogPostContainer from './BlogPostContainer.js'

<BlogPostContainer id={1} />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章