Redux 是什么?
Redux 是一个使用叫做 “action” 的事件来管理和更新应用状态的模式和工具库 它以集中式 Store(centralized store)的方式对整个应用中使用的状态进行集中管理,其规则确保状态只能以可预测的方式更新。
Redux 帮你管理“全局”状态 - 应用程序中的很多组件都需要的状态。
Redux 中文官网: https://cn.redux.js.org/tutorials/essentials/part-1-overview-concepts以下为代码展示(仅供参考)
src/store/index.js
import counterReducer from '../features/counter'
export default configureStore({
reducer: {
counter: counterReducer
}
})
src/index.js
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux'
import store from './store'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
src/features/counter.js
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
increment: state => {
state.value += 1
},
decrement: state => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
}
}
})
// 每个 case reducer 函数会生成对应的 Action creators
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
页面应用数据
src/pages/Home.jsx
import { decrement, increment } from '../features/counter'
import {useDispatch, useSelector} from 'react-redux'
function Home(){
const count = useSelector(state => state.counter.value)
const dispatch = useDispatch()
function dispatch() {
dispatch(increment())
}
return(
<div>
<div> 展示内容 {count} </div>
<div className={'del-btn'} onClick={() => { dispatch()}}>
操作
</div>
</div>
)
}
export default Home