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自有方法),