Redux 三个基本原则:
- 唯一数据源
- 保持状态只读
- 数据改变只能通过纯函数完成
- 唯一数据源
应用的状态数据应该只存储在唯一的一个Store上。
- 保持状态只读
就是说不能直接去修改状态,要修改Store状态,必须要派发一个action对象完成。
- 数据改变只能通过纯函数完成
在Redux中,每个reducer的函数签名如下:
reducer(state,action)
第一个参数是state当前的状态,第二个参数action是接收到的action对象,因为reducer是一个纯函数,所以函数的返回结果必须完全有参数state和action决定,而且不产生任何副作用,也不修改action和state值。
在./src/Actions.js中每个action构造函数会返回一个action对象
import * as ActionTypes from "./ActionTypes.js"
export const increment = ()=>{
return{
type:ActionTypes.INCREMENT,
counterCaption:counterCaption
}
}
export const increment = ()=>{
return{
type:ActionTypes.DECREMENT,
counterCaption:counterCaption
}
}
如上面的代码,只是返回一个对象,如何使用这个对象交给调用者。
store对象上的dispatch将action派发给store。
创造一个 src/Store.j s 文件,这个文件输出全局唯一的那个
Store
import {createStore} from "redux";
import reducer from "./Reducer.js";
const initValues={
"First":0,
"Second":10,
"Third":20
}
const store = createStore(reducer,initValues)
Redux 提供
createStore
这个函数,用来生成 Store.
Redux 库提供的 createStore 函数,这个函数第一个参数代表更新状态的 reducer函数,第二个参数是状态的初始值
createStore
函数接受两个参数,返回新生成的 Store 对象
src/Reducer.j s 中定义的 reducer 函数
import * as ActionTypes from "./ActionTypes.js";
export default (state,action) = >{
const {counterCation} = action;
switch(action.type){
case ActionTypes.INCREMENT:
return{...state,[counterCation]:state[counterCation]+1}
case ActionTypes.DECREMENT:
return{...state,[counterCation]:state[counterCation]-1}
default:
return state
}
}
Counter组件,存在于src/view/Counter.js中:
import React, { Component, PropTypes } from 'react';
import store from '../Store.js';
import * as Actions from '../Actions.js';
const buttonStyle = {
margin: '10px'
};
class Counter extends Component {
constructor(props) {
super(props);
this.onIncrement = this.onIncrement.bind(this);
this.onDecrement = this.onDecrement.bind(this);
this.onChange = this.onChange.bind(this);
this.getOwnState = this.getOwnState.bind(this);
this.state = this.getOwnState();
}
getOwnState() {
return {
value: store.getState()[this.props.caption]
};
}
onIncrement() {
store.dispatch(Actions.increment(this.props.caption));
}
onDecrement() {
store.dispatch(Actions.decrement(this.props.caption));
}
onChange() {
this.setState(this.getOwnState());
}
shouldComponentUpdate(nextProps, nextState) {
return (nextProps.caption !== this.props.caption) ||
(nextState.value !== this.state.value);
}
componentDidMount() {
store.subscribe(this.onChange);
}
componentWillUnmount() {
store.unsubscribe(this.onChange);
}
render() {
const value = this.state.value;
const {caption} = this.props;
return (
<div>
<button style={buttonStyle} onClick={this.onIncrement}>+</button>
<button style={buttonStyle} onClick={this.onDecrement}>-</button>
<span>{caption} count: {value}</span>
</div>
);
}
}
Counter.propTypes = {
caption: PropTypes.string.isRequired
};
export default Counter;
其中:store.getState()能够获取store上存在的所有状态(是store自有方法),