如果ownProps
指定了参数,则react-redux会将传递给组件的props传递给connect
函数。因此,如果您使用这样的连接组件:
import ConnectedComponent from './containers/ConnectedComponent'
<ConnectedComponent
value="example"
/>
在ownProps
您的内部mapStateToProps
和mapDispatchToProps
功能将是一个对象:
{ 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} />