文章目录
action
- action一用来描述动作行为的对象, 是一个必须具有type字段的JavaScript平面对象。type的值:是一个事件名称(自己定义)
该type字段应该是一个字符串,为该操作提供一个描述性名称,例如"todos/todoAdded". 我们通常把那个类型的字符串写成"domain/eventName",其中第一部分是这个动作所属的特征或类别,第二部分是发生的具体事情。
- action对象可以具有其他字段,其中包含有关所发生事件的附加信息。按照惯例,我们将这些信息放在一个名为payload.
例如:
const addTodoAction = {
type: 'todos/todoAdded', //todoAdded添加事件,添加一个任务
payload: 'Buy milk' //附加信息
}
action 创建函数
action 创建函数:是一个创建并返回动作对象的无副作用的纯函数。我们通常使用这些,因此我们不必每次都手动编写动作对象:
const addTodo = text => {
return {
type: 'todos/todoAdded',
payload: text
}
}
reducer 函数
reducer 函数就是 一个根据当前状态(state)和动作类型(action.type),催化出想要的数据
reducer是一个无副作用的纯函数,它接收当前state和一个action对象,在必要时决定如何更新状态,并返回新状态(state, action) => newState
您可以将 reducer 视为事件侦听器,它根据接收到的action.type(事件)类型处理事件。
reducer函数必须始终遵循一些特定规则:
1. 应该只根据state和action参数计算新的状态值
2. 不允许修改现有的state的值
3. 他们不得执行任何异步逻辑、计算随机值或导致其他“副作用”
注意:一个应用程序应该只有一个根reducer 函数
function counterReducer(state = 0, action) {
//根据action.type(事件)来书写逻辑
if (action.type === 'counter/increment') {
return {
...state,
value: state.value + 1
}
}
return state
}
store 存放所有全局state的对象。
store 是一个 JavaScript 对象,具有一些特殊的功能和能力,使其不同于普通的全局对象:
你绝不能直接修改或更改保存在 Redux 存储中的状态
修改state更新的唯一方法是创建一个action对象,然后调用store.dispatch(action)将action分派到store中以告诉它发生了什么。
action 被调度时,store 运行 root reducer函数,并让它根据旧state和 action 计算新状态
最后,store 通知订阅者状态已更新,以便 UI 可以使用新数据进行更新。
创建store
方法一:使用redux创建store
const store = Redux.createStore(counterReducer)
方法二:使用Redux Toolkit创建store
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({ reducer: counterReducer })
store 中的重要方法:
1. getState:store.getState()用来获取当前状态值的
2. dispatch:store.dispatch方法的参数是action对象,更新状态的唯一方法是调用store.dispatch(action)时,store 会根据action.type的值运行它的 reducer 函数并将新的 state 值保存在store里面
dispatch函数就是根据行为动作分派任务,更改数据
store.dispatch(action)返回action对象,不过,中间件可能会扰乱返回值。
3.subscribe:就是一个监听器,store.subscribe(callback),有一个无参数回调函数,在分发完action时运行,他会返回一个函数,用于取消监听
//action创建函数
const increment = () => {
return {
type: 'counter/increment'
}
}
//将action对象传入
store.dispatch(increment())
const unsubscribe= store.subscribe(callback)
unsubscribe() //取消监听
console.log(store.getState())
// {value: 2}
其他api请见官网
Selectors函数
Selectors函数是知道如何从存储状态值中提取特定信息片段的函数。随着应用程序越来越大,这可以帮助避免重复逻辑,因为应用程序的不同部分需要读取相同的数据:
const selectCounterValue = state => state.value
const currentValue = selectCounterValue(store.getState())
console.log(currentValue)
// 2
combineReducers 函数
将所有reducer合并成一个根reducer
手动合并
import todosReducer from './features/todos/todosSlice'
import filtersReducer from './features/filters/filtersSlice'
const initState ={
todos:null,
filters:null
}
export default function rootReducer(state = {}, action) {
// 返回新的状态
return {
// the value of `state.todos` is whatever the todos reducer returns
todos: todosReducer(state.todos, action),
// For both reducers, we only pass in their slice of the state
filters: filtersReducer(state.filters, action)
}
}
使用combineReducers合并
import { combineReducers } from 'redux'
import todosReducer from './features/todos/todosSlice'
import filtersReducer from './features/filters/filtersSlice'
const rootReducer = combineReducers({
// Define a top-level state field named `todos`, handled by `todosReducer`
todos: todosReducer,
filters: filtersReducer
})
export default rootReducer
Middleware 中间件函数
Middleware函数内部实际上就是替换了store中的dispatch、getState和subscribe方法
一般情况,我们只需自定义dispatch,来增强一些功能
中间件函数
使用中间件函数applyMiddleware()
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducer'
import { print1, print2, print3 } from './exampleAddons/middleware'
const middlewareEnhancer = applyMiddleware(print1, print2, print3)
// Pass enhancer as the second arg, since there's no preloadedState
const store = createStore(rootReducer, middlewareEnhancer)
export default store
thunk 函数
“thunk”是一个编程术语,意思是“执行一些延迟工作的一段代码”。
thunk函数接受store对象中的dispatch, getState方法作为参数,应用程序代码不会直接调用Thunk函数。相反,它们被传递给store.dispatch()
一个thunk函数可以包含任何任意的逻辑,sync或async,并且可以在任何时候调用dispatch或getState。
const thunkFunction = (dispatch, getState) => {
// logic here that can dispatch actions or read state
}
store.dispatch(thunkFunction)
- 我们通常用thunk创建函数来生成一个thunk函数
// fetchTodoById is the "thunk action creator"
export function fetchTodoById(todoId) {
// fetchTodoByIdThunk is the "thunk function"
return async function fetchTodoByIdThunk(dispatch, getState) {
const response = await client.get(`/fakeApi/todo/${todoId}`)
dispatch(todosLoaded(response.todos))
}
}