Redux

redux ['ridʌks] adj 回来的,回家的

Actions

首先,定义一些actions。 Actions是数据,只是用来存储的信息。发送它们到store中使用store.dispatch()

这里有一个添加新的todo项的action例子

const ADD_TODO = 'ADD_TODO'

{
    type: ADD_TODO,
    text: 'Build my first Redux app'
}

Actions是一个简单的js对象。Actions必须有type这个字段。值定义为字符串常量。如果你的项目很大,你也许需要移动它们到一个分离的模块。

import {ADD_TODO,REMOVE_TODO} FROM '../actionTypes'
注意点
小的项目定义在一个文件里比较好,大的还是分离出来。

除了type字段,action里的结构取决于你,如果你有兴趣,可以看看Flux Standard Action。

我们把actions存储在数组里,在真实的项目中,会生成一个唯一的id,所以我们添加一个index字段在action中。

{
  type: COMPLETE_TODO,
  index: 5
}

传递很少的数据很好的想法成为了可能,例如,传递index比传递整个todo对象好。

最后,我们再添加一个action类型用来改变当前todos的可见性。

{
 type: SET_VISIBILITY_FILTER,
 filter: SHOW_COMPLETED
}

Action Creators

Action creators是创建actions的方法,很容易混淆"action"和"action creator"术语。所以你最好使用适当的术语。

在Redux action creators简单的返回一个action:

function addTodo(text){
  return {
    type:ADD_TODO,
    text
  }
}

这使得它们便捷和容易测试。

在传统的Flux action creators常在调用的时候出发调度,例如:

function addTodoWithDispatch(){
  const action = {
    type: ADD_TODO,
    text
  }
  dispatch(action)
}

在Redux中不是这样的。 相反,真正的调用调度,是将结果传递给dispatch()方法:

 dispatch(addTodo(text))
 dispatch(completeTodo(index))

或者,你可以创建一组action creator自动调度

const boundAddTodo = () => dispatch(addTodo(text))
const boundCompleteTodo = (index) =>(completeTodo(index))

现在你可以直接的调用它们:

boundAddTodo(text)
boundCompleteTodo(index)

dispatch()方法可以在stroe里直接像这样stroe.dispatch()调用,但是你也可以使用帮助如react-redux中的connect()去访问。你可以使用bindActionCreators()中自动绑定。

Action creators can also be asynchronous and have side-effects. You can read about async actions in the advanced tutorial to learn how to handle AJAX responses and compose action creators into async control flow. Don’t skip ahead to async actions until you’ve completed the basics tutorial, as it covers other important concepts that are prerequisite for the advanced tutorial and async actions.

源码

actions.js

/*
 * action types
 */

export const ADD_TODO = 'ADD_TODO'
export const COMPLETE_TODO = 'COMPLETE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'

/*
 * other constants
 */

export const VisibilityFilters = {
  SHOW_ALL: 'SHOW_ALL',
  SHOW_COMPLETED: 'SHOW_COMPLETED',
  SHOW_ACTIVE: 'SHOW_ACTIVE'
}

/*
 * action creators
 */

export function addTodo(text) {
  return { type: ADD_TODO, text }
}

export function completeTodo(index) {
  return { type: COMPLETE_TODO, index }
}

export function setVisibilityFilter(filter) {
  return { type: SET_VISIBILITY_FILTER, filter }
}

REF

results matching ""

    No results matching ""