Redux三大基本原则
- 唯一数据源,只要一个Store
- 保持状态只读,改变状态只能通过 stroe.dispatch 方法 提交 aciton
- 状态只用纯函数reducers 去改变。
Store 详解
- Store作为一个唯一的数据源,为开发者提供了五个方法供使用,先说三个常用的方法
- store.dispatch ( ) -------用于派发 actions
- store.getState ( ) -------从Store 里获取状态
- store.subscribe ( ) ------- 监听Store状态,状态改变就会触发这个方法。
利用Redux 写了一个如下图的小例子
store 代码块
import { createStore } from 'redux'
import { reducers } from './reducers'
const initValue = {
First: 0,
Second: 10,
Third: 20
}
const store = createStore(reducers, initValue)
export default store;
actionTypes 代码块
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
actions 代码块
import * as Types from './actionTypes.js'
export const increment = function(counterCaption){
return {
type: Types.INCREMENT,
counterCaption
}
}
export const decrement = function(counterCaption){
return {
type: Types.DECREMENT,
counterCaption
}
}
reducers 代码块
export const reducers = (state, action)=>{
let { counterCaption } = action;
switch(action.type){
case 'INCREMENT':
return {...state, [counterCaption]: ++state[counterCaption] }
break;
case 'DECREMENT':
return {...state, [counterCaption]: --state[counterCaption] }
break;
default:
return state;
}
}
Counter 组件 代码块
import React from 'react'
import store from '../store/store'
import * as Actios from '../store/actions'
class Counter extends React.Component {
constructor(props){
super(props)
this.state = this.getOwnState()
}
getOwnState(){
return {
value: store.getState()[this.props.caption]
}
}
onincrement=()=>{
let { caption } = this.props;
store.dispatch(Actios.increment(caption))
}
onDecrement=()=>{
let { caption } = this.props;
store.dispatch(Actios.decrement(caption))
}
onChange=()=>{
this.setState(this.getOwnState(),()=>{
this.props.init && this.props.init()
});
}
componentDidMount(){
store.subscribe(this.onChange);
}
componentWillUnmount(){
store.unsubscribe(this.onChange);
}
render(){
const value = this.state.value;
const { caption } = this.props;
return(
<div>
<button onClick={ this.onincrement }>+</button>
<button onClick= { this.onDecrement }>- </button>
<span> {caption} count : {value}</span>
</div>
)
}
}
export default Counter;
App 组件 代码块
import React, { Component } from 'react';
import Counter from './component/Counter'
import store from './store/store'
class App extends Component {
constructor(){
super()
this.state = {
num: 0
}
}
getOwerState(){
let state = store.getState();
let result = 0;
for( var key in state ) {
result += state[key]
}
this.setState({
num: result
})
}
handleChange=()=>{
this.getOwerState()
}
componentDidMount(){
this.getOwerState()
}
render() {
return(
<div>
<p>总数:{this.state.num}</p>
<Counter init={this.handleChange} caption="First"/>
<Counter init={this.handleChange} caption="Second"/>
<Counter init={this.handleChange} caption="Third"/>
</div>
)
}
}
export default App;