Provider
是什麼
react-redux 提供的一個 React 組件php
做用
把 store 提供給其子組件css
//使用 redux 的 createStore 方法建立的一個 store
const store = createStore(todoApp,{})
// store 做爲一個 prop 傳給 Provider 組件
render(
<Provider store={store}>
<App/>
</Provider>, document.getElementById('app'))
connect
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
做用
把「指定的state & 指定的action」和 React組件 鏈接起來 ==> 容器組件html
參數說明
mapStateToProps
這是一個function,返回一個object;react
(state, [ownProps]) => ({ }) // 一般省略第二個參數
apache
做用 把指定的state做爲props注入到 UI組件 中redux
const mapStateToProps = state => {
return {
title: state.title,
list: state.list
};
}
固然,沒必要將 state 中的數據原封不動地傳入組件,能夠根據 state 中的數據,動態地輸出組件須要的(最小)屬性。markdown
const mapStateToProps = (state) => {
return {
greaterThanFive: state.count > 5 // 假如只須要知道count大不大於5就成
}
}
函數的第二個參數 ownProps,是 React的UI組件本身的 props。有的時候,ownProps 也會對其產生影響。
好比,當你在 store 中維護了一個用戶列表,而你的組件只關心一個用戶。app
const mapStateToProps = (state, ownProps) => {
// state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}
return {
user: _.find(state.userList, {id: ownProps.userId})
}
}
class MyComp extends Component {
static PropTypes = {
userId: PropTypes.string.isRequired,
user: PropTypes.object
};
render(){
return <div>用戶名:{this.props.user.name}</div>
}
}
const Comp = connect(mapStateToProps)(MyComp);
mapDispatchToProps
這能夠是一個function,還能夠是object,less
做用 把指定的action做爲props注入到UI組件中ide
// 方法
const mapDispatchToProps = dispatch => {
return {
destroyTodo : () => dispatch({
type : 'DESTROY_TODO'
})
}
}
// 對象
mergeProps
是一個函數,用來篩選哪些參數傳遞給組件。這個函數接受3個參數
const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({
...ownProps,
...stateProps,
...dispatchProps
})
stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是當前組件本身的屬性。
這個函數默認把這三個返回值拼裝到一塊兒傳遞給組件,可修改。
options
一個對象,有兩個布爾,一個是pure,一個是withRef。
- pure爲false,只要connect接受到屬性,無論是否有變化,必然刷新connect組件。
- withRef爲true時,在裝飾傳入的 React 組件時,Connect 會保存一個對該組件的 refs 引用,能夠經過 getWrappedInstance 方法來得到該 refs,並最終得到原始的 DOM 節點。
使用
const newApp = connect(store)(UI)