redux
redux是负责组织state的工具,是javascript应用的状态容器,提供可预测的状态管理。她保证程序行为一致性且易于测试
1.什么时候需要redux
1.有大量的,随着时间变化的数据;
2.你的state需要有一个单一可靠数据来源;
3.把所有state放在最顶层组件已无法满足需求;
4.某个组建状态需要共享;
2.redux基本使用方法
2.1 安裝
npm install redux --save
2.2 使用
store/index.js
import { createStore } from 'redux';
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;
ReactReduxPage .js
import React from 'react'
import store from '../store'
export default class ReactReduxPage extends React.Component {
// 订阅通知state发生改变
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
console.log('state change')
// 发生改变页面重新渲染
this.forceUpdate();
})
}
render() {
console.log(store)
return (
<div>
<h2>ReactReduxPage</h2>
<p>{store.getState()}</p>
<button onClick={() => store.dispatch({type: 'ADD'})}>add</button>
</div>
)
}
}