redux时react中负责状态管理的工具
一、下载
npm I @reduxjs/toolkit react-redux
二、配置
1、目录
modules里面可以定义多个store,index内负责收集这些store
2、store配置
这里定义了一个count参数和关于count的方法,一会用来测试
js
import { createSlice } from '@reduxjs/toolkit'
const counterStore = createSlice({
name: 'counter',
initialState: {
count: 0,
},
reducers: {
setChannels (state,action){
state.channelList = action.payload
},
increment(state) {
state.count++
},
decrement(state) {
state.count--
},
addToNum(state,action){
console.log(state,action);
state.count = action.payload
}
}
})
const { increment, decrement,addToNum } = counterStore.actions
const counterReducer = counterStore.reducer
export { increment, decrement,addToNum }
export default counterReducer
3、redux中index.js配置
js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterStore";
const store = configureStore({
reducer: {
counter: counterReducer,
}
})
export default store
4、启动类中index.js配置
js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
import './global.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
三、使用
1、调用store的数据
js
import { useSelector } from 'react-redux'
function App() {
const { count } = useSelector(state => state.counter)
return (
<div>
<div className='App'>
{count}
</div>
</div>
)
}
export default App;
2、调用store里面的方法
js
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement } from './store/modules/counterStore'
function App() {
const { count } = useSelector(state => state.counter)
const dispatch = useDispatch()
return (
<div>
<div className='App'>
<button onClick={() => dispatch(decrement())}>-</button>
<button onClick={() => dispatch(increment())}>+</button>
{count}
</div>
</div>
)
}
export default App;
3、改变store里面的值
js
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement, addToNum } from './store/modules/counterStore'
function App() {
const { count } = useSelector(state => state.counter)
const dispatch = useDispatch()
return (
<div>
<div className='App'>
<button onClick={() => dispatch(decrement())}>-</button>
<button onClick={() => dispatch(increment())}>+</button>
{count}
<button onClick={() => dispatch(addToNum(20))}>add To 20</button>
</div>
</div>
)
}
export default App;