combineReducers() 用法详解
作者:互联网
当业务应用变得复杂,我们就需要对 reducer 函数进行拆分,拆分后的每一块独立负责管理 state 的一部分。
combineReducers()
辅助函数的作用就是:把一个由多个不同 reducer 函数作为 value 的 object 合并成为一个总的 reducers 函数。然后可以对这个 reducers 调用 createStore()
。
合并后的 reducers 可以调用各个子 reducer,并把他们的结果合并成一个 state 对象。state 对象的结构由传入的多个 reducer 的 key 决定。
最终,state 对象的结构会是这样的:
{
reducer1: ...
reducer2: ...
}
通过为传入对象的 reducer 命名不同来控制 state key 的命名。例如,你可以调用 combineReducers({ todos: myTodosReducer, counter: myCounterReducer }) 将 state 结构变为 { todos, counter }。
通常的做法是命名 reducer,然后 state 再去分割那些信息,因此你可以使用 ES6 的简写方法:combineReducers({ counter, todos })
。这与 combineReducers({ counter: counter, todos: todos })
一样。
参数
combineReducers()
接收一个对象,它的值对应不同的 reducer 函数,这些reducer 函数会被合并为一个。然后被引入到 store 中,放到 createStore()
中。
combineReducers({
reducer1,
reducer2,
...
})
返回值
(Function):一个调用 reducers 对象里所有 reducer 的 reducer,并且构造一个与 reducers 对象结构相同的 state 对象。
示例
// goodsList/reducer.js
const defaultState = {
goodsList: []
}
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'GET_GOODS_LIST':
return {
...state,
goodsList: action.data
}
default:
return state;
}
}
export default reducer;
// goodsList/action.js
const getGoodsList = () => {
return (dispatch) => {
fetch('http://demo.com/api/demoDemoItem')
.then(response => response.json())
.then(res => {
dispatch({
type: 'GET_GOODS_LIST',
data: res
})
})
}
}
export {
getGoodsList
}
// redux/reducers.js
import { combineReducers } from "redux";
import goodsListReducer from "../pages/goodsList/reducer";
export default combineReducers({
goodsListReducer
})
// redux/store.js
import { createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk';
import reducers from './reducers';
const store = createStore(reducers, applyMiddleware(thunk));
export default store;
import React, {Component} from 'react';
import './index.css'
import Header from "./components/header";
import TabBar from "./components/tabBar";
import GoodsItem from "./components/goodsItem";
import { connect } from 'react-redux';
import { getGoodsList } from "./action";
class GoodsList extends Component{
componentDidMount(){
// 从 store 中获取数据
this.props.getGoodsList();
}
render(){
return (
<div className="container">
<Header />
<TabBar />
{
this.props.goodsList.map((item, index) => {
return (
<GoodsItem goodsItem={item} key={index}/>
)
})
}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
// 注意 state.gooderListReducer 才存在 goodsList数据
goodsList: state.goodsListReducer.goodsList
}
}
const mapDispatchToProps = (dispatch) => {
return {
getGoodsList() {
dispatch(getGoodsList())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(GoodsList);
注意 state.gooderListReducer 才存在 goodsList数据
参考文章:Redux框架之combineReducers() 用法讲解
标签:goodsList,combineReducers,reducer,用法,state,详解,import,reducers 来源: https://www.cnblogs.com/aurora-ql/p/14110920.html