react 学习之redux使用方法
1 . 什么是redux
redux 是 JavaScript应⽤的状态容器,提供可预测化的状态管理。它保证程序⾏为⼀致性且易于测试。
2. redux安装
npm install redux --save
3. redux使用小案例(累加器)
使用步骤:
- 需要⼀个store来存储数据
- store⾥的reducer初始化state并定义state修改规则
- 通过dispatch⼀个action来提交对数据的修改
- action提交到reducer函数⾥,根据传⼊的action的type,返回新的state
第一步:创建store,src/store/index.js
import {createStore} from 'redux'
//reducer初始化state并定义state修改规则
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + 1
case 'MINUS':
return state - 1
default:return state
}
}
const store = createStore(counterReducer)
export default store
第二步:page获取store数据
import React, { Component } from "react";
import store from "../store/ReduxStore";
export default class ReduxPage extends Component {
componentDidMount() {
//订阅(subscribe)状态变更
store.subscribe(() => {
console.log("subscribe");
this.forceUpdate();
//this.setState({});
});
}
add = () => {
store.dispatch({ type: "ADD" });
};
minus = () => {
store.dispatch({ type: "MINUS" });
};
render() {
console.log("store", store);
return (
<div>
<h3>ReduxPage</h3>
<p>{store.getState()}</p>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>
</div>
);
}
}
完成以上步骤就利用redux实现了一个简单的累加器。更多的使用方法请查看官方文档。
























