自助建站cn,做一个企业网站要多少钱,怎么做交互式网站,二次开发是指一、概念
Redux 是一个用于管理 JavaScript 应用状态的库。在 Redux 中#xff0c;整个应用的状态都存储在一个对象中#xff0c;称为 store。
Store 实际上是一个 JavaScript 对象#xff0c;它存储了整个应用的状态。它是唯一的#xff0c;意味着应用中只有一个 store。…一、概念
Redux 是一个用于管理 JavaScript 应用状态的库。在 Redux 中整个应用的状态都存储在一个对象中称为 store。
Store 实际上是一个 JavaScript 对象它存储了整个应用的状态。它是唯一的意味着应用中只有一个 store。每当状态发生变化它会存储最新的状态。
使用 Redux 时你可以通过调用 store.getState() 来获取当前应用的状态通过调用 store.dispatch(action) 来更新应用的状态其中 action 是一个描述发生了什么的对象。
总的来说store 是 Redux 应用的核心部分它存储了整个应用的状态并提供了读取和更新状态的方法
二、定义store
创建一个store.js文件
import { createStore } from redux;// 定义初始状态
const initialState {count: 0
};// 定义reducer
function reducer(state initialState, action) {switch (action.type) {case INCREMENT:return {...state,count: state.count 1};case DECREMENT:return {...state,count: state.count - 1};default:return state;}
}// 使用createStore创建store
const store createStore(reducer);export default store三、页面中获取store中定义的数据
import React from react;
import { useSelector } from react-redux;function Counter() {/*** 使用useSelector这个钩子来获取store中的state* 接收一个回调函数state就是我么你定义的state* 需要那个属性可以直接return对象的属性*/const count useSelector(state state.count);return (divdivCount: {count}/div/div);
}export default Counter;三、store常用的方法
1、store.getState
// 返回应用当前的 state。 它与 store 的最后一个 reducer 返回值相同。
store.getState()2、store.dispatch
// dispatch action。这是触发 state 变化的惟一途径。store.dispatch()3、store.subscribe
添加一个变化监听器。每当 dispatch action 的时候就会执行state 树中的一部分可能已经变化。你可以在回调函数里调用 getState() 来拿到当前 state。返回一个可以销毁监听的函数。
const unsubscribe store.subscribe(handleChange)三、模块化处理
1、combineReducers
使用combineReducers可以对redux进行模块化管理在 Redux 中你可以使用多个 Reducer 来处理不同的数据然后使用 combineReducers 函数将它们合并起来。
2、创建user模块
创建user.js
const defaultState {};const userReducer (state defaultState, action) {switch (action.type) {case UPDATE_USER:return { ...state, ...action.payload };default:return state;}
};export default userReducer;3、在store.js中引入并使用combineReducers合并
import { legacy_createStore as createStore, combineReducers } from redux;
import user from ./user;const rootReducer combineReducers({// 知己诶使用es6的语法那么这个模块的名字就是useruser,
});// 创建 store
const store createStore(rootReducer);// 导出 store
export default store;4、页面中获取store
import React from react;
import { useSelector, useDispatch } from react-redux;function Counter() {/*** 使用useSelector这个钩子来获取store中的state* 接收一个回调函数state就是我么你定义的state* 需要那个属性可以直接return对象的属性* */// const count useSelector(state state.count);/*** 如果我们对redux分过模块* 那么我们使用state.user先找到对应的模块再去* 获取里面的属性*/const state useSelector((state) state.user)return (divpName: {state.name}/p/div);
}export default Counter;