第一步: 创建仓库 vuex ===== redux
1, 下载安装 redux 模块 和 react-redux模块
cnpm install redux --save
cnpm install react-redux --save
2,创建数据仓库文件 src/store/index.js 从redux导入创建函数creatStore, 合并函数combineReducers
import { createStore, combineReducers } from "redux";
3, 定义reducer函数
function countReducer(state = 0, action){
switch (action.type) {
case "ADD":
return state + action.number
default:
return state
}
}
4, 把多个reducer函数合并成一个
var reducers = combineReducers({
count: countReducer,
})
5, 创建并导出数据仓库
export default createStore(reducers)
第二步: 读取仓库数据
1, 在入口文件index.js中导入状态仓库store和状态更新供应组件Provider
import { Provider } from "react-redux";
import store from "./store/index";
2, 在入口文件index.js中,使用Provider 包裹App根组件, 并设置store
<Provider store={store}>
<App />
</Provider>
3, 在使用状态管理的组件中导入状态仓库联合函数connect (高阶组件)
import { connect } from "react-redux";
4, 在导出组件之前,创建状态数据映射函数映射状态数据
function mapState(store){
return {
name: store.name,
}
}
5, 在导出组件之前, 使用联合函数connect把仓库中的状态数据拼接到组件的props中
MyCom= connect(mapState)(MyCom)
6, 在组件中通过this.props调用状态仓库中的数据
{this.props.name}
第三步: 更新仓库数据
1, connect高阶组件会向当前组件props中传入dispatch函数,用于状态数据的更新, 参数对应reducer函数的第二个参数action
在需要更新的位置, 更新仓库中的数据
this.props.dispatch({
type: "CHANGE",
value: this.refs.input.value
})
附加: 监听仓库中数据的更新
2, 在需要监听更新的组件中导入状态仓库
import store from "../../store/index"
store.subscribe(()=>{
console.log("数据已更新")
})
注1: store.subscribe() 添加监听后会返回一个函数, 调用返回的函数可以结束监听
注2: 如果报hooks的错,请降低react-redux版本为5.0重试
757

被折叠的 条评论
为什么被折叠?



