2016-12-17 11 views
26

Redux'ta connect işlevine iletilen mapStateToProps ve mapDispatchToProps işlevinin ikinci bir argüman olarak ownProps aldığını görüyorum.mapStateToProps ve mapDispatchToProps öğesinde ownProps arg'inin kullanımı nedir?

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

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

için isteğe bağlı [ownprops] argüman nedir? Ben zaten biri olarak orada şeyleri açıklığa kavuşturmak için ek örneğin arıyorum

the Redux docs

+0

daha spesifik ol; Bağlandığınız belgelerde bu argümanın açıklamaları hakkında net olmayan nedir? – jonrsharpe

+0

Sadece argümanın kullanıldığı ek bir pratik örnek arıyordum. – therewillbecode

+0

O zaman bunu açıklığa kavuşturabilir misin? – jonrsharpe

cevap

47

ownProps parametre belirtilmemişse, sizin connect fonksiyonları içine bileşene geçirildi sahne geçecek-redux tepki . Böyle bir bağlı bileşeni kullanmak Yani eğer,: En mapStateToProps ve mapDispatchToProps fonksiyonları iç

import ConnectedComponent from './containers/ConnectedComponent' 

<ConnectedComponent 
    value="example" 
/> 

ownProps bir nesne olacak:

{ value: 'example' } 

Ve dönmek ne karar vermek için bu nesneyi kullanabilirsiniz bu işlevler.

// 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 

Şimdi bu bileşeni kullanır:

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

Bunu yayının için bir şeyler yapmak Redux eylem yaratıcıları geri dönebilirler: Bir blog yazısı bileşeni Örneğin


, gibi:

import BlogPostContainer from './BlogPostContainer.js' 

<BlogPostContainer id={1} /> 
+0

Not - defaultProps kendiProp'larına dahil değildir – Swards