LoginSignup
0
0

More than 5 years have passed since last update.

learning Redux from todo[4]

Last updated at Posted at 2016-09-15

刚才说到了 Store

接下来说 数据流

Redux 使用单向数据流

这就意味着在 app 里所有的数据都会经过同样 的生命周期模式. 让你的程序逻辑更加可以预测和容易理解.对于数据的处理同样要优化精华. 而不是让你死在多份同样的数据, 你手里的数据同样能够被他人来修改. 都不知道自己怎么死的.

如果还是没有被说服,建议读一下 1 2 同时建议读一下 Redux 不简单是 Flux 的变种它同样说明了一些为什么要单向数据流的好处.

Redux 应用里的数据大致会走4步:

  1. 当你调用` store.dispatch(action). 触发了一个动作.

一个动作就是一个简单的对象,说明了会发生什么.


 { type: 'LIKE_ARTICLE', articleId: 42 }
 { type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
 { type: 'ADD_TODO', text: 'Read the Redux docs.' }

描述了一个动作, 已经一些参数用来指明动作作用的对象.
好比这样说: 一个动作就是'某某喜欢找个文章', 看 redux 的文章`等等.

你可以在 redux app 的任何地方使用` store.dispatch(action), 包括组件或者 XHR 的回调, 甚至是一个循环调用.

  1. Redux store 调用你给它的 reducer 函数

store 是会传递两个参数给reducer 的. 第一个是当前的状态, 第二个是 action, 然后返回 action 作用之后的最新状态. 再来看个例子:

 let previousState = { // 当前的状态
   visibleTodoFilter: 'SHOW_ALL',  //要显示什么类型
   todos: [  //所有的 todo
     {
       text: 'Read the docs.',
       complete: false
     }
   ]
 }

 // 这是一个添加 todo 的动作
 let action = {
   type: 'ADD_TODO',
   text: 'Understand the flow.'
 }

 // 获取最新的状态
 let nextState = todoApp(previousState, action)


一定要保证reducer 都是 pure 的函数,也就是说每次给同样的参数返回结果都是一样的.

  1. 根 reducer 可以组合多个 reducer 到一个单独的状态树里.

如何组织*根 reducer *完全是个人喜好, Redux 提供一个combineReducers() 函数用来帮助组织分散的 Reducer. 下面再看看他们是如何被组织起来的:

 function todos(state = [], action) {
   // Somehow calculate it...
   return nextState
 }

 function visibleTodoFilter(state = 'SHOW_ALL', action) {
   // Somehow calculate it...
   return nextState
 }

 let todoApp = combineReducers({
   todos,
   visibleTodoFilter
 })

当你触发一个动作, 然后 todoAPP 就会调用由combineReducers返回的对应的 reducer:

let nextTodos = todos(state.todos, action)
let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action)

其实上面的情况就是返回

 return {
   todos: nextTodos,
   visibleTodoFilter: nextVisibleTodoFilter
 }

  1. Redux Store 会把所有的 reducer 返回的 state 写会单独完整的 state 里.

至此,算是我们已经完成的 backend 逻辑, 接下来我们会学习如何结合react 完全 UI 部分.


index

learning Redux from todo

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0