// 1. 创建数据仓库
import { createStore, legacy_createStore } from 'redux';
// 2. 创建实例
const store = createStore(reducer)
// reducer:计算者,规定了数据的修改规则,
// action 要通知的对象
function reducer(state = { c: 0 }, action) {
switch (action.type) {
// 6. 查看 action (要通知的对象)中 是否 有要通知的对象
case 'counter':
// 7. 返回一个对象 ,会覆盖 原来的 state,所以,需要复制一份
return {
...state,
// 修改 数据 的逻辑
c: state.c + action.payload
}
// 3. 一上来就会执行一次,初始化数据,走的是默认值
default: return state
}
}
setInterval(() => {
// 4. dispatch 会用于数据的修改。每次执行都会调用 renducer 函数
// type(固定)--名字; payload(随意)--要传递的用于修改数据 的参数
store.dispatch({
type: "counter",
// 后面是要传递的参数
payload: 2
})
// 5. getState用户获取当前store中的所有数据
console.log(store.getState());
}, 1000)
react-例子
- 配置好store
// store
import { createStore, legacy_createStore } from 'redux';
// 2. 创建实例
export const store = createStore(reducer)
export function reducer(state = { c: 1 }, action) {
switch (action.type) {
case 'counter':
return {
...state,
c: state.c + action.payload
}
default: return state
}
}
- 下载好包:yarn add react-redux
- 在最顶层引入
// main.jsx
import { Provider } from 'react-redux'
import { store } from './store/index'
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider store={store} >
<App />
</Provider>
)
- 在对应的组件使用:
import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
export default function Redux() {
const count = useSelector(state =>state.c)
const dispatch = useDispatch();
useEffect(() => {
let timer = setInterval(() => {
dispatch({
type: "counter",
payload: 2
})
console.log(123, count); // 闭包,此处 count 会一直打印 1
}, 1000)
return () => { clearInterval(timer) }
}, [])
return (<div>Redux {count}</div>)
}
推荐: