cdn 配置redux 或 redux-toolkit

<!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> 

 -

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值