React的通信是一对一的,向原始的电话通信!
Redux,类似一个通信云存储,将所有的公共状态存在云上,只要状态一改变,个组件都能取到状态的最新值。
使用Redux需要掌握哪些重要的API:
- store:store对象是保存公共数据的地方,一个应用只能创建一个store,创建方法如下:
import {createStore} from 'redux';
const store = crateStore(function);
- state: state是store映射的数据集合,一个state只能对应一个view,创建方法如下:
import {createStore} from 'redux';
const store = crateStore(function);
const state = store.getState(); //通过store.getStore()拿到state
action:state和view是结对的,view发生变化时,会用action发出通知。action是改变state的唯一方法
- action必要属性:type,其他属性可以自由设置。
store.dispatch(): store.patch()是view发出action的唯一方法,示例如下:
store.dispatch({
type:'student_age',
age: 12
name: 'hanmeimei'
});
- reducer: reducer是一个计算state的函数,有两个参数,当前state和action。
- 当store收到action通知后,一定要返回一个全新的state。
- store接收到action传来的数据,然后根据逻辑计算数据,该过程就称为reducer.
- 示例如下:
import {createStore} from 'redux';
const reducer = (state = defaultState, action) => {
switch(action.type){
case 'student_age':
return state;
default:
return
}
}
const store = createStore(reducer); //生成store时,传入reducer
- store.subscribe():store.subscribe()监听state变化,state一旦变化就自动触发该函数。
- 示例:
import {createStore} from 'redux';
const store = createStore(reducer);
store.subscribe(listen);
- Redux的运行原理:
- store中的重要方法:
目前,React框架dva就融入了Redux的设计思想,似的dva框架更方便使用!
Basic Example
- 官网教程示例
import { createStore } from 'redux'
/**
* This is a reducer, a pure function with (state, action) => state signature.
* It describes how an action transforms the state into the next state.
*
* The shape of the state is up to you: it can be a primitive, an array, an object,
* or even an Immutable.js data structure. The only important part is that you should
* not mutate the state object, but return a new object if the state changes.
*
* In this example, we use a `switch` statement and strings, but you can use a helper that
* follows a different convention (such as function maps) if it makes sense for your
* project.
*/
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)
// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.
store.subscribe(() => console.log(store.getState()))
// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1
本文首发于Laqudee Blog,给作者GitHub)里的项目➕🌟!