本篇文章给大家带来的内容是关于redux的核心讲解(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
概念
redux是一种架构模式,可以和react、vue结合使用。
解决的问题
优雅地修改共享数据状态,避免状态在父子组件的连锁改动(子组件多的话改起来麻烦)及外部改动造成的不必要(难以排除)问题,所以所有的改动强横通过一个方法(dispatch)修改。

实现步骤
//state(数据)和action(控制修改)后的数据
function reducer (state, action) {
/!* 初始化 state 和 switch case *!/
}
// 通过reducer获取state
// 执行action
// 监听数据变化
const store = createStore(reducer)
// 监听数据变化重新渲染页面
// 通过观察者模式监听数据变化,避免没有状态改变的频繁渲染
store.subscribe(() => renderApp(store.getState()))
// 首次渲染页面
renderApp(store.getState())示例
const usersReducer = (state, action) => {
if (!state) return [];
switch (action.type) {
case "ADD_USER":
return [...state, action.user]
case "DELETE_USER":
return [...state.slice(0, action.index), ...state.slice(action.index + 1)]
case "UPDATE_USER":
let user = {
...state[action.index],
...action.user,
}
return [
...state.slice(0, action.index),
user,
...state.slice(action.index + 1),
]
default:
return state
}
}
//state(数据)和dispatch(控制修改)封装起来
function createStore (reducer) {
let state = null
const listeners = []
const subscribe = (listener) => listeners.push(listener)
const getState = () => state
const dispatch = (action) => {
state = reducer(state, action) // 覆盖原对象
// console.log(listeners)
listeners.forEach((listener) => {
// console.log(listener)
listener()
})
}
dispatch({}) // 初始化 state
return { getState, dispatch, subscribe }
}
const store = createStore(usersReducer);
console.log(store.getState());
//增
store.dispatch({
type: 'ADD_USER',
user: {
username: 'Lucy',
age: 12,
gender: 'female'
}
});
console.log(store.getState());
//改
store.dispatch({
type: 'UPDATE_USER',
index: 0,
user: {
username: 'Tomy',
age: 12,
gender: 'male'
}
});
console.log(store.getState());
//删
store.dispatch({
type: 'DELETE_USER',
index: 0 // 删除特定下标用户
});
console.log(store.getState());以上就是redux的核心讲解(代码示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号