Redux:with React,一

作者数次强调,redux和React没有关系(明明当初就是为了管理react的state才弄出来的吧),它可以和其他插件如 Angular, Ember, jQuery一起使用。好啦好啦知道啦。Redux的初衷就是为了管理UI的状态,触发state的更新作为对action的回应。

文档举的例子是一个todo App。

安装react-redux:

npm install --save react-redux redux

Presentational and Container Components:

React bindings for Redux embrace the idea of separating presentational and container components. If you're not familiar with these terms, read about them first, and then come back. They are important, so we'll wait!

当我们想把redux应用到react中时,要接受一种思想:app中的组件可以分为两类

一类是用于展示内容的组件(P):负责结构和样式,与redux无关,响应props的数据,调用props的方法,组件由开发者设计

一类是作为容器的组件(C):负责数据获取和状态更新,与redux有关,响应state更新,能dispatch action,由react redux生成

C组件能和redux store联系,它是P组件与redux store的桥梁。但不一定要在组件树的顶层。如果C组件太复杂,建议引入另一些C组件来拆分它的逻辑,像split reducer一样。

注意:尽管开发者也可以使用store.subscribe()手写C组件,但是作者并不建议,他更推荐我们通过react redux 的 connect() function 来生成C组件,因为通过react redux生成的C组件可以实现性能最优化,这是手写不容易达到的。

举的是todolist的例子

设计组件的层级:

复习一下Thinking in React

设计展示组建:

  • TodoList is a list showing visible todos.
    • todos: Array is an array of todo items with { id, text, completed } shape.
    • onTodoClick(id: number) is a callback to invoke when a todo is clicked.
  • Todo is a single todo item.
    • text: string is the text to show.
    • completed: boolean is whether todo should appear crossed out.
    • onClick() is a callback to invoke when a todo is clicked.
  • Link is a link with a callback.
    • onClick() is a callback to invoke when link is clicked.
  • Footer is where we let the user change currently visible todos.
  • App is the root component that renders everything else.

P组件只负责渲染视图,并不关心数据从哪来的,也不关系数据怎么变更。

Designing Container Components:

  • VisibleTodoList filters the todos according to the current visibility filter and renders a TodoList.
  • FilterLink gets the current visibility filter and renders a Link.
    • filter: string is the visibility filter it represents.

C组件负责将P组件和Redux 联系起来。用户可以通过C组件触发state更新,P组件通过容器获取变更的数据并重新渲染视图。

Designing Other Components:

作者承认有时候很难界定一个组件属于P还是C,对于很简单的组件,如一个todolist的输入框,没必要将其分解。但随着组件的复杂度增大,不难将之分解成P和C两部分。

组件的实现:

1.实现P组件:

http://redux.js.org/docs/basics/UsageWithReact.html#componentstodojs

由于P组件的意义只是渲染DOM,因此P组件其实是没有状态的,只有从父组件/容器组件获取的props,所以可以使用function组件直接返回JSX而不使用Class组件

2.实现C组件:

C组件可以通过subscribe()获取Redux store state树的一部分,作为P组件的props。

作者再次强调使用Redux插件的 connect()构造容器组件。connect方法的意义在于将P组件和C组件连接起来。

使用connet()方法时,需要定义一个名为mapStateToProps 的特殊函数,这个函数描述了怎么把当前的redux store state转换为P组件需要的props:

 1 const getVisibleTodos = (todos, filter) => {
 2   switch (filter) {
 3     case 'SHOW_ALL':
 4       return todos
 5     case 'SHOW_COMPLETED':
 6       return todos.filter(t => t.completed)
 7     case 'SHOW_ACTIVE':
 8       return todos.filter(t => !t.completed)
 9   }
10 }
11 
12 const mapStateToProps = state => {
13   return {
14     todos: getVisibleTodos(state.todos, state.visibilityFilter)
15   }
16 }

如上,getVisibleTodos函数是不是很像Reducer中被解构成更小功能的单位,其实就是个内部逻辑单元而已。

只是获取state作为P组件的props还不够。C组件还得能触发dispatch以更新state,所以还有另一个特殊函数mapDispatchToProps,它的参数是dispatch()函数

1 const mapDispatchToProps = dispatch => {
2   return {
3     onTodoClick: id => {
4       dispatch(toggleTodo(id))
5     }
6   }
7 }

有了这两个函数之后,容器组件的方法才算基本完善,调用connect()将之作为参数传进去:

1 import { connect } from 'react-redux'
2 
3 const VisibleTodoList = connect(
4   mapStateToProps,
5   mapDispatchToProps
6 )(TodoList)
7 
8 export default VisibleTodoList

这是connect()生成容器组件的基本套路,connect()的返回值是个函数,再执行一次返回容器。第二个括号中的传参是个P组件,表示生成的C组件是该P组件的容器。

访问store:

在应用程序中,往往有多个层级的组件,使用react redux后当我们的容器想访问store时,一种方法是将store作为props传下去,让子组件可以访问它。但是这样太麻烦了,因为你必须每一级都把它传递下去。一种推荐的做法是,使用<Provider>组件。我们只需要在根组件渲染时使用它:

 1 import React from 'react'
 2 import { render } from 'react-dom'
 3 import { Provider } from 'react-redux'
 4 import { createStore } from 'redux'
 5 import todoApp from './reducers'
 6 import App from './components/App'
 7 
 8 let store = createStore(todoApp)
 9 
10 render(
11   <Provider store={store}>
12     <App />
13   </Provider>,
14   document.getElementById('root')
15 )

总结:

1.在设计应用的组件时,先理清应用的模块的划分,然后对每个模块进行实现。

2.对应用划分好模块之后,针对每个模块,先设计好它的state的结构,知道哪些state是负责处理data的,哪些是负责UI渲染的。

3.设计好一个模块的state之后,创建需要的action对象,并创建对应的reducer函数,然后生成store。

4.创建展示组件,负责渲染内容。

5.利用connect()方法生成容器组件,包含mapstate和mapdispatch方法,用以获取当前state、触发state更新。

6.在最顶层index页面ReactDOM.render渲染应用时,组件最外层被<Provider store={store}></Provider>包裹,以全局提供store的引用。