做外贸网站推广什么比较好,小程序注册失败,asp网站新闻置顶,肇庆企业自助建站redux是一个状态管理框架#xff0c;它可以帮助我们清晰定义state和处理函数#xff0c;提高可读性#xff0c;并且redux中的状态是全局共享#xff0c;规避组件间通过props传递状态等操作。
快速使用 在React应用的根节点#xff0c;需要借助React的Context机制存放整个… redux是一个状态管理框架它可以帮助我们清晰定义state和处理函数提高可读性并且redux中的状态是全局共享规避组件间通过props传递状态等操作。
快速使用 在React应用的根节点需要借助React的Context机制存放整个store信息。需要进行以下配置。
index.js
import React from react
import ReactDOM from react-domimport {Provider} from react-redux
import {store} from ./store
import App from ./appconst rootElement document.getElementById(root);ReactDOM.render(Provider store {store}App//Provider,rootElement)store文件需要配置下Redux包括reducer和action以及state
store.js
import {createStore} from reduxconst initialState {value: 0}// Reducer
function counterReducer(state initialState, action){switch (action.type){case counter/incremented:return {value: state.value 1};case counter/decremented:return {value: state.value - 1};default:return state}
}// Action
export const incrementAction {type:counter/incremented}
export const decrementAction {type: counter/decremented}// Redux 定义
export const store createStore(counterReducer)
在业务逻辑中需要通过useSelector和useDispatch自定义hook获取state和dispatch
Counter.js
import React from react
import {useDispatch, useSelector} from react-redux
import {decrementAction, incrementAction} from ./store;export function Counter() {const count useSelector(state state.value)const dispatch useDispatch()return (divbutton onClick{() dispatch(incrementAction)}/buttonspan{count}/spanbutton onClick{() dispatch(decrementAction)}-/button/div)}
使用效果