Redux设计和使用的三项原则

1.store必须是唯一的。

import { createStore } from 'redux';
import reducer from './reducer';

//创建公共存储工具,如果window下有这个变量,则执行这个变量对应的方法。
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

export default store;

 

2.只有store才能改变自己的内容。(store拿到reducer返回的数据,自己更新自己的数据)。

3.Reducer必须是纯函数。

什么是纯函数呢?纯函数指的是,给定固定的输入,就一定会有固定的输出,而且不会有任何副作用。

import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from "./actionTypes";

const defaultState = {
    inputValue:'234',
    list:[2,3]
}

//state表示存储在整个应用(Store)中数据
//state表示store上次存储的数据,action表示用户说的话
//reducer可以接受state,但是绝不能修改state。新的state返回给了store,替换store中老数据。
export default (state = defaultState, action)=>{
    if (action.type === CHANGE_INPUT_VALUE) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.inputValue = action.value;
        return newState;
    } else if (action.type === ADD_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.push(newState.inputValue);
        newState.inputValue = '';
        console.log(newState);
        return newState;
    } else if (action.type === DELETE_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.splice(action.index, 1);
        return newState;
    }
    return state;
}

 

以下写法就不是纯函数了:

因为即使固定下面的输入state和action,因为new Date()的存在,此时该函数就不是纯函数了。

 

扫描二维码关注公众号,回复: 8699609 查看本文章

对参数修改,说明有副作用。这时此时也不是纯函数了。

 

下面是Redux的核心的api:

1.createStore:

帮助我们创建一个store。

 

2.store.dispatch

帮助我们派发action。交给reducer处理。

 

3.store.getState

store.getState可以帮助我们获取到store中的全部内容。

 

4.store.subscribe

帮助我们订阅store的改变。只要store发生改变,这个store.subscribe注册的回调函数就会被执行。

发布了161 篇原创文章 · 获赞 154 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/zhangying1994/article/details/87451772