使用步骤
1. 定义一个reducer函数(根据当前想要做的修改返回一个新的状态)
2.使用createStore方法传入reducer函数生成一个store实例对象
3.使用store实例的subcribe方法订阅数据的变化(数据一旦变化,可以得到通知)
4.使用store实例的dispactch方法提交action对象触发数据变化(告诉reducer你想怎么改变数据)
5.使用store实例的getState方法获取最新的状态数据更新到视图
<script>
//1. 定义reducer函数
function reducer (state = {count:0}, action){
if (action.type === "INCREMENT"){
return {count: state.count +1}
}
if (action.type === "DECREMENT"){
return {count: state.count +1}
}
return state
}
//2. 使用reduce函数生成store实例
const store = Redux.createStore(reducer)
//3.订阅, 回调函数可以在每次state发生变化的时候自动执行
store.subscribe(()=>{
console.log('state变化了')
//5.getState获取最新状态
document.getElementById('count').innerText = store.getState().count
})
//4.通过dispatch函数提交action更改状态
const inBtn = document.getElementById('increment')
inBtn.addEventListener('click', ()=>{
store.dispatch({type:'INCREMENT'})
})
</script>
npm i @reduxjs/toolkit react-redux
import {createSlice} from "@reduxjs/toolkit";
const counterStore = createSlice({
name: 'counter',
//初始化state
initialState: {count: 0},
//修改状态的方法,同步方法,支持直接修改
reducers: {
inscrement(state) {
state.count++
},
decrement(state) {
state.count--
},
addToNum(state, action){
state.count = action.payload
}
}
})
//解构出来actionCreater函数
const {inscrement, decrement, addToNum} = counterStore.actions
//获取reduce
const reducer = counterStore.reducer
//以按需导出的方式导出actionCreater
export {inscrement, decrement, addToNum}
//默认导出
export default reducer
import {configureStore} from "@reduxjs/toolkit";
import conterReducer from "./modules/counterStore"
const store = configureStore({
reducer: {
counter: conterReducer
}
})
export default store
import store from "./store"
import {Provider} from 'react-redux'
import {useSelector, useDispatch} from "react-redux";
import {decrement, inscrement, addToNum} from "./store/modules/counterStore";
function Son() {
const {count} = useSelector(state => state.counter)
const dispatch = useDispatch()
return (<div>
<button onClick={() => dispatch(decrement())}>-</button>
<span>{count}</span>
<button onClick={() => dispatch(inscrement())}>+</button>
<button onClick={() => dispatch(addToNum(10))}>add to 10</button>
</div>)
}
function App() {
return (
<div>
<Provider store={store}>
<Son/>
</Provider>
</div>
)
}
export default App;