首页 > 其他 > 详细

redux学习

时间:2017-09-23 16:39:12      阅读:478      评论:0      收藏:0      [点我收藏+]

redux主要用于解决组件之间通信问题:

一、store:保存数据的地方,每个应用只能有一个store

在redux中,使用createStore函数来生成store

import { createStore } from redux
let store = createStore(todoApp)

二、state:所有的状态,通过store.getState()函数来获取

三、action:  state的变化会出发view的更新,用户只能接触view层,action就是view层发出通知,表示该更新某个state了(改变 State 的唯一办法,就是使用 Action。它会运送数据到 Store)

/*
 * action 类型
 */
export const ADD_TODO = ADD_TODO;
export const isLoading = isLoading;
/*
 * action 创建函数
 */
export function addTodo(text) {
    return { type: ADD_TODO, text }
}

export function loading(text) {
    return {type: isLoading, text}
}

四、store.dispatch() 

     view层通过store.dispatch()来发出action

store.dispatch(addTodo(Learn Redux));

五、Reducer:reducer用于更新state并返回一个新的state

import {ADD_TODO} from ./action
let initState = {
    counter: 0,
    isLoading: false,
    todos: []
}
function reducer(state, action) {
    if (!state) {
        state = initState
    }
    switch (action.type) {
        case isLoading:
            return Object.assign({}, state, {
                isLoading: action.text
            });
            return state
        default:
            return state
    }
}
export default reducer

 

redux学习

原文:http://www.cnblogs.com/running1/p/7581413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!