redux明白store reducer action之间的关系

可参考 知乎大神Wang Namelos[https://www.zhihu.com/people/wang-namelos/activities]回答:https://www.zhihu.com/question/41312576?sort=created

正如回答所说,我们要先弄明白react需要什么,然后看redux如何管理react数据库:
简言之如回答所说:
a. 需要回调通知state (等同于回调参数) -> action
b. 需要根据回调处理 (等同于父级方法) -> reducer
c. 需要state (等同于总状态) -> store
具体可参考回答,里面已经说得很通俗易懂了,这里主要说下如何实际编写action、reducer、store:

在此之前先说下他们之间是怎么操作流通的:
1、当view需要发起行为时,需要在当前位置触发action,即store.dispatch(addNote())
2、当Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。而这种 State 的计算过程就叫做 Reducer。而Reducer方法是由store.dispatch方法触发来自动执行的。为此,Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。
import { createStore } from 'redux'; const store = createStore(reducer);
Reducer 是一个函数,且为纯函数,它接受 Action 和当前 State 作为参数,Reducer 函数里面不能改变 State,必须返回一个全新的state对象。
3、state更新,触发view发生改变,而在此之前必须把数据store和操作事件action绑定到需要使用的组件上,就需要用到connect函数(connect方法可参考这篇文章:https://yq.aliyun.com/articles/59428):
意思是先接受两个参数(数据绑定mapStateToProps和事件绑定mapDispatchToProps),再接受一个参数(将要绑定的组件本身):
export default connect(mapStateToProps,mapDispatchToProps)(App)
其中:
mapStateToProps 就是将state(补充:即store中的该组件需要的数据)作为props绑定到组件上
mapDispatchToProps是可选的,将 action 作为 props 绑定到组件上,如果不传这个参数redux会把dispatch作为属性注入给组件,可以手动当做store.dispatch使用
//mapDispatchToProps 为actions里面的函数绑定dispatch,可直接调用this.props.actions.xxx(),即等同于没绑定情况下this.props.dispatch(xxx()),不需要手动dispatch
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(actions, dispatch)
});
//mapStateToProps 可返回当前数组需要的几个state属性值
const mapStateToProps = state => {
return{
notes : state.notes
}
};
以上,便可以在组件内触发action,更新state,来更新view的变化

action: 指全局发布的动作指令,主要就是定义所有事件行为的,例如:
export const ADD_NOTE = “ADD_NOTE”;
export const DELETE_NOTE = “DELETE_NOTE”;

let nextTodoId=0;
export const addNote = (title,text) => ({
type: ADD_NOTE,
id: nextTodoId++,
title:title,
note: text
});
export const deleteNote = (id) => ({
type: DELETE_NOTE,
id: id
});

以上定义了两个action函数,分别是添加笔记和删除笔记,正如前面所说,mapDispatchToProps 将 action 作为 props 绑定到组件,可以直接在组件中调用触发dispatch,代码如下:

class App extends Component{
    constructor(props){
        super(props);
    }
    onAddNote(title,text){
        this.props.actions.addNote(title,text);
    }
    deleteNote(id){
        this.props.actions.deleteNote(id);
    }
    render(){
        return(
            <div className="container">
                <h1 className="header">记事本</h1>
                <NoteAdd onAddNote={(title,text)=>this.onAddNote(title,text)}/>
                <NoteList notes={this.props.notes} onDeleteNote={(id)=>this.deleteNote(id)}/>
            </div>
        );
    }
}

reducer: action指令发起会触发reducer对应函数执行,例如:
import { combineReducers } from “redux”;
import { INIT_NOTES, ADD_NOTE, DELETE_NOTE } from “…/actions”;

//处理笔记初始化、添加及删除请求
function notes(state = [ ], action){
    //每一次的操作无论是添加、删除还是初始化,全部的笔记内容会被重新更新一次
    switch(action.type){
        // case INIT_NOTES:
        //     return [ ...action.notes ];
        case ADD_NOTE:
            return [
                ...state,
                {
                    id: action.id,
                    title: action.title,
                    note: action.note
                }
            ];
        case DELETE_NOTE:
            var newState=[];
            state.map((note) =>{
                if(note.id != action.id){
                    newState.push(note);
                }
            });
            return newState;
        default:
            return state;
    }
}

const rootReducer = combineReducers({ notes });
export default rootReducer;

当发起this.props.actions.addNote(title,text)时,reducer会执行case ADD_NOTE:返回一个新的state对象,(原文:store监测到state更新便会重新加载更新部分虚拟dom,修正:store中的state更新,由于我们通过mapStateToProps将store中的state作为props传给组件,此时props发生变化,react 会重新渲染该组件,并更新部分虚拟dom),使页面更新;
其中 combineReducers是 Redux 提供的一个方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 Reducer,例如:

import { combineReducers } from 'redux';

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})

export default todoApp;

最后回到mapStateToProps
const mapStateToProps = state => {
    return{
        notes : state.notes
    }
};

这里的state,打印出来可以看到:其实即为reducer输出的notes对象:

{notes:[
  id:0
  note:" ddddd"
  title:"ddd"
]}

如果是多个reducer的合集,那就是输出的多个对象的合集:
{notes:[{
  id:0
  note:" ddddd"
  title:"ddd"
}],
note:[{
  id:0
  note:" ddddd"
  title:"ddd"
}]
}

以上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值