redux是一个可预测的状态管理工具,唯一可以改变state的方式就是dispatch一个action,action描述了以何种方式改变state,交由reducer去改变state。
创建redux应用
npm i redux
src/index.js:
import {
createStore} from 'redux'
const initState = {
list: []
}
// reducer,createStore的第一个参数,当store初始化的时候redux会调用reducer,传入state为undefined,action.type为一个@@redux/INIT开头的随机字符串
// 所以在这里可以设置state的默认值,防止下次reducer改变数据的时候报错
// reducer应当返回一个state,来作为新的state。
function todo(state = initState, action){
switch(action.type){
case 'todoAdd':
return {
list: state.list.concat(action.text)
}
case 'todoRemove':
return {
list: state.list.filter((v) => v !== action.text)
}
default:
return state
}
}
let store = createStore(todo)
//订阅store更新
store.subscribe(() => {
console.log(store.getState())
})
//派发action,这个action会被传入到reducer的第二个参数
store.dispatch({
type: 'todoAdd',
text: '吃饭',
})
store.dispatch({
type: 'todoAdd',
text: '睡觉',
})
store.dispatch({
type: 'todoAdd',
text: '打豆豆',
})
store.dispatch({
type: 'todoRemove',
text: '睡觉',
})
控制台打印结果为:
合并reducer
假如说有多个reducer,一个是todo,另外一个是用户数据,我们可以使用redux提供的combineReducers来合并reducer,src下新建一个文件夹为store,src/store/index.js为创建的store,src/store/todo.js和src/store/user.js分别为todo的reducer和user的reducer。
src/store/index.js代码为:
import {
createStore, combineReducers} from 'redux'
import todo from './todo'
import user from './user'
const reducer = combineReducers({
todo,
user,
})
const store = createStore(reducer)
export default store
src/store/user.js代码为
const initState = {
name: 'xiaobai',
age: 18,
}
function user(state = initState, action){
switch(action.type){
case 'userAgeAdd':
return {
...state,
age: state.age + 1,
}
case 'userNameChange':
return {
...state,
name: action.name,
}
default:
return state