Skip to content

Latest commit

 

History

History
55 lines (34 loc) · 1.99 KB

2017-01-22.md

File metadata and controls

55 lines (34 loc) · 1.99 KB

react redux todo

目标:一个 todo 页面

你需要实现一个 ReactDOM,将其插入到页面的根节点中

UI 组件和容器组件

这个 ReactDOM 不仅需要呈现 UI (UI 组件),又涉及业务逻辑和内部状态(容器组件),所以我们需要的是一个内部包含 UI 组件的容器组件,让外部的容器组件负责业务,内部的 UI组件则获取数据进行渲染。我们可以通过 'react-redux' 提供的 connect 函数来实现这样的容器组件。身为一个容器组件,他需要知道两件事:

  1. 输入逻辑(mapStateToProps):如何将外部的 state 转换为 UI 组件的参数
  2. 输出逻辑(mapDispatchToProps):如何将用户的动作变成 action 对象,从 UI 组件中 dispatch 出去
const App = connect(mapStateToProps, mapDispatchToProps)(UIComponent)

function mapStateToProps(state, props) {}
function mapDispatchToProps(dispatch, props) {}

class UIComponent extend Component { render(){} }

Action

用户的 action 被设定为长这个样子 { type: 'ADD_TODO', ...},type 指定是什么行为,其他字段存放行为数据。

Store

容器组件要拿到 store 中的数据进行处理,需要在外部套上一个 <Provider> 组件 该组件的 store 属性即为应用的 store。

我们可以通过 'redux' 的 createStore 来创建一个应用的 store。store 是一个保存数据的地方。创建一个 store 你需要指定初始 state(非必选)和收到一个 action 之后如何给出一个新 state(即 reducer)。

const store = createStore(reducer, initState)

<Proviser store={store}>
    <App />
</Provider>

Reducer

上面说了我们需要一个“根据接收到的 action 给出新 state”的东西,就是 reducer。

function reducer (state = {}, action) {
    ...
    return newState;
}

state tree 中的不同的部分你可以用不同的 reducer 对应操作,然后再用 'redux' 中的 combineReducers({reducerA, reducerB}) 结合起来。