Provider
是什么
react-redux 提供的一個 React 組件
作用
把 store 提供給其子組件
//使用 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組件 連接起來 ==> 容器組件
參數說明
mapStateToProps
這是一個function,返回一個object;
(state, [ownProps]) => ({ }) // 通常省略第二個參數
作用 把指定的state作為props注入到 UI組件 中
const mapStateToProps = state => {
return {
title: state.title,
list: state.list
};
}
當然,不必將 state 中的數據原封不動地傳入組件,可以根據 state 中的數據,動態地輸出組件需要的(最小)屬性。
const mapStateToProps = (state) => {
return {
greaterThanFive: state.count > 5 // 假如只需要知道count大不大於5就成
}
}
函數的第二個參數 ownProps,是 React的UI組件自己的 props。有的時候,ownProps 也會對其產生影響。
比如,當你在 store 中維護了一個用戶列表,而你的組件只關心一個用戶。
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,
作用 把指定的action作為props注入到UI組件中
// 方法
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)