2016-12-17 53 views
26

我看到在Redux中傳遞給connect函數的mapStateToPropsmapDispatchToProps函數取ownProps作爲第二個參數。mapStateToProps和mapDispatchToProps中ownProps arg的用法是什麼?

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

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

什麼是可選的[ownprops]參數?

我要尋找另外的例子來把事情說清楚前面已經一個存在the Redux docs

+0

你能更加詳細一些;您鏈接到的文檔中對該論點的解釋還不清楚? – jonrsharpe

+0

我只是在尋找另一個使用參數的實例。 – therewillbecode

+0

那麼你能否把這個問題弄清楚? – jonrsharpe

回答

47

如果指定了ownProps參數,反應 - 終極版將被傳遞到組件的道具的方式傳遞到connect功能。所以,如果你使用這樣的連接組件:

import ConnectedComponent from './containers/ConnectedComponent' 

<ConnectedComponent 
    value="example" 
/> 

裏面你mapStateToPropsmapDispatchToProps功能的ownProps將是一個對象:

{ 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} /> 
+0

注 - defaultProps不包含在ownProps中 – Swards

相關問題