Redux中 combineReducers的使用
什么时候去使用combineReducers?
如果不同的action所处理的属性之间没有联系,我们可以把Reducer函数拆分。
不同的函数负责处理不同的属性,最终把他们合并成一个大的Reducer即可,这就是combineReducers。
配置思路
- 首先安装redux的依赖包
- 创建store/index.js中,配置项目支持redux的使用
- 导入redux纯函数,state数据,actions代表方法,返回操作后的state对象,合并的方式返回{...state,修改对象}
- createStore调用reducers作为参数创建store对象
- store抛出,使用的页面import导入即可,这个就是redux使用
- store.getState()获取数据 store.dispatch()调用action的方法即可
附页:目录表
分别新添了cart.js文件以及user.js文件
user.js即:
// 1.导入createStore方法
import { createStore } from "redux";
// 2.创建一个reducer纯函数的方法,state初始化数据,actions修改数据的行为
const reducer=function (state,actions){
//定义初始化的数据
if(!state){
state={
count:10,
list:[
{name:"小欣欣",age:20},
{name:"小张张",age:21},
]
}
}
//定义actions的逻辑代码区域,处理逻辑的信息
switch(actions.type){
//调用执行+1的逻辑
case "PLUS":
return{
...state,
// count:state.count+1,
count:state.count+actions.payload,
}
case "MIN":
return{
...state,
count:state.count-1
}
//添加列表
case "ADD":
state.list.push(actions.payload)
return{
...state,
list:state.list
}
break
default:{
return{
...state
}
}
}
}
//3.创建一个store的对象
const store=createStore(reducer)
// 4.抛出store的对象值
export default reducer;
cart.js即:
export default function(state,actions){
if(!state){
state={
num:100
}
}
switch(actions.type){
default:
return state;
break
}
}
index.js即:(index.js文件分别引入我们的user.js以及cart.js)
cart.js和user.js分别写的是我们的数据操作简单来说就是判断逻辑
// 1.导入createStore方法
import { combineReducers, createStore } from "redux";
import cart from "./cart";
import user from "./user"
// 2.创建一个reducer纯函数的方法,state初始化数据,actions修改数据的行为
const reducer=combineReducers({
user,
cart
})
//3.创建一个store的对象
const store=createStore(reducer)
// 4.抛出store的对象值
export {store};
Home.jsx即:
import React from 'react'
import {store} from "../../store"//引入我们的store文件夹
import { useRef } from 'react'
export default function Home(props) {
// 获取redux数据
let state=store.getState()
console.log(state);
let {count,list}=state.user
console.log(count,list);
let nameinp=useRef(null)
let ageinp=useRef(null)
// console.log(count);
const add=()=>{
console.log(nameinp.current.value,ageinp.current.value);
// 提交到redux中去
store.dispatch({type:"ADD",payload:{name:nameinp.current.value,age:ageinp.current.value}})
}
return (
<div>
{/* <h3>
主页面
Redux:{count}
</h3>
<button onClick={()=>{store.dispatch({type:"PLUS",payload:2})}}>count++</button>
<button onClick={()=>{store.dispatch({type:"MIN"})}}>count-1</button> */}
<hr/>
<div>
<input type="text" ref={nameinp} placeholder='请输入姓名'/><br/>
<input type="text" ref={ageinp} placeholder='请输入年龄'/><br/>
<button onClick={add}>添加</button>
</div>
<ul>
{list.map((item,index)=>{
return(
<li key={index}>{item.name}--{item.age}</li>
)
})}
</ul>
</div>
)
}
这边有一个需要特别注意的点即:
它是不可以直接去使用,访问的时候会报undefined的错误
我是一个小趴菜,希望可以对和我一样的新手小白有帮助🤭
版权声明:本文为Clover_zlx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。