<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/redux@4.2.1/dist/redux.min.js"></script>
<!-- 引入 Redux Toolkit -->
<script src="https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@latest/dist/redux-toolkit.umd.min.js"></script>
<!-- <script>
// Redux 的三个核心概念:Store、Reducer、Action
// (1) 定义 Reducer(管理状态)
function counterReducer(state = { count: 0 }, action) {
console.log(action,"action");
// switch (action.type) {
// case 'INCREMENT':
// return { count: state.count + 1 };
// case 'DECREMENT':
// return { count: state.count - 1 };
// default:
// return state;
// }
}
// (2) 创建 Store
const store = Redux.createStore(counterReducer);
// (3) 订阅状态变化(可选)
store.subscribe(() => {
console.log('Current state:', store.getState());
document.getElementById('app').innerHTML = `
<h1>Count: ${store.getState.count}</h1>
<button onclick="dispatchIncrement()">+1</button>
<button onclick="dispatchDecrement()">-1</button>
`;
});
// (4) 定义 Action 派发函数
function dispatchIncrement() {
store.dispatch({ type: 'INCREMENT' });
}
function dispatchDecrement() {
store.dispatch({ type: 'DECREMENT' });
}
// 初始化渲染
store.dispatch({ type: '@@INIT' }); // 触发默认状态
</script> -->
<script>
console.log(Redux);
console.log(RTK);
const { configureStore, createSlice } = RTK;
// 使用 createSlice 简化 Reducer 和 Action 创建
const counterSlice = createSlice({
name: 'counter1',
initialState: { count: 0 },
reducers: {
increment: (state,payload) => { state.count += 1
console.log(payload,"payload");
console.log(state,"state");
},
decrement: (state) => { state.count -= 1 },
},
});
const store = configureStore({
reducer: counterSlice.reducer,
});
store.subscribe(() => {
console.log('Current state:', store.getState());
document.getElementById('app').innerHTML = `
<h1>Count: ${store.getState().count}</h1>
<button onclick="dispatchIncrement()">+1</button>
<button onclick="dispatchDecrement()">-1</button>
`;
});
// 直接使用 slice 生成的 action creators
function dispatchIncrement() {
store.dispatch(counterSlice.actions.increment(666));
}
function dispatchDecrement() {
store.dispatch(counterSlice.actions.decrement());
}
// 初始化渲染
store.dispatch({ type: '@@INIT' }); // 触发默认状态
</script>
-