25. Redux 的用途 & 入门实作 (上)

Redux


Redux 跟 React 并没有关系。你可以用 React、Angular、Ember、jQuery 或甚至原生 JavaScript 来撰写 Redux 应用程序。

Redux 最基本的用途就是 集中管理state,主要的使用方式是: 将 UI 描述成一个 state 的 function,每当 state 更新,执行对应的 action。

优点

  • 大型专案管理方便
    Redux会用一个store储存专案中所有的state,也就是资料会被集中在同一个地方。
  • 画面和资料分离,便於整理资料
    画面交给React Component;资料管理交给Redux。

实作步骤


修改codepen的范例,简单制作一个姓名清单。

  1. 创建 Reducer

    • Reducer 是一个函式。
    • 在 Redux 中用以保管 state , 并指定要执行的action

    (范例有载入NODE-UUID CDNs,顺便练习key绑id。)

    // 创建资料库
    const initialState = [
      {
        name: "Winnie",
        id: uuid.v4()
      },
      {
        name: "Mary",
        id: uuid.v4()
      },
      {
        name: "Angel",
        id: uuid.v4()
      }
    ];
    
    // reducer(初始资料状态,要对state执行的动作){}
    const reducer = (state = initState, action) => {
        switch (action.type){
            default:
                return state 
        }
    }
    

    这里的范例只有设定预设的情况,没有设定其他action,先简单理解就好。

  2. 创建 store

    • store负责整合所有的 Reducer
    import { createStore } from 'redux'
    
    // 创建 store : 整合reducer
    const store = createStore(reducer, initialState);
    
    • 每个专案都应该只能有一个 store 存在。
    • 如果有不同类型的资料,会以 Reducer 区分。最後将很多 Reducer 打包并创建成 store 。

  3. 定义要从 store 中取得的资料
    mapStateToProps()

    const mapStateToProps = state => {
        return {
          contacts: state
        };
    }
    
    
    • mapStateToProps是一个函数。
    • 会把store传进state,并回传名为contacts的属性(property),对应原来的属性。
    • 每当store变化,进行重新渲染(以 contacts 为 key 从 props 流进 component)。
  4. 连结component

    • 建立Component
    const Contacts = (props) => {
        return (
          <ul>
            {props.contacts.map((contact, id) => (
              <div key={id} className="box">
                <p>{contact.name}</p>
              </div>
            ))}
          </ul>
        );
    }
    

    帮清单写成一个Component,然後引入App。

    import React from 'react'
    
    class App extends React.Component {
      render() {
        return (
          <section className="section">
            <h1 className="title">Contacts</h1>
            <Contacts
              contacts={this.props.contacts}
            />
          </section>
        );
      }
    }
    

    传入Contacts的this.props.contacts 就是之後mapStateToProps里回传的contacts属性。

    • 连结 component 与 mapStateToProps
    import { connect } from 'react-redux'
    
    // 
    const AppContainer = connect(mapStateToProps)(App);
    

    AppContainer接收connect处理好 mapStateToProps, App的结果。

  5. 用 Provider 将 store 的资料传进 component

    • 设置 Provider ( 一种 react-redux 中的组件 ),它会
    import { connect, Provider } from 'react-redux'
    import ReactDOM from 'react-dom'
    
    // 根据需求单将资料流进 component
    ReactDOM.render(
      <Provider store={store}>
        <AppContainer />
      </Provider>,
      document.getElementById("root")
    );
    

    Provider 是一种 react-redux 中的组件,它会

    1. 接收上方在 Redux 中创建的 store
    2. 根据和 component 绑在一起的 mapStateToProps,从 store 取出要求的资料
    3. 透过 props 流向 component

Provider 在最外层并指定了 store 。

Provider 永远都在最外层,也永远都只有一个

为了保持资料来源都是从 Provider 流进内部的 component ,这也是为什麽每个专案中 store 应该都只能有一个。

最後附上 codepen完整程序码

【如内文有误还请不吝指教>< 并感谢阅览至此的各位:D 】

参考资料

---正文结束---


<<:  Day 11 ROS Cpp Parameter Server

>>:  通过SafariViewController查询网站 Day22

[Day 27] RecyclerView 下 - itmetouchhelper

重要 method onSwiped(ViewHolder, int) 当产生侧滑效果了,会回调此方...

【Day 18】深度学习(Deep Learning)--- Tip(三)

昨天提到了ReLU还有它的一些variant,那接下来要讲的是另外一个更进阶的想法,叫做Maxou...

[C#] 产生 MSSQL Table DML (SELECT, INSERT, UPDATE, DELETE) SQL 语法

当我们要在资料表内操作资料时,最常执行的指令就是 Select, Insert, Update, D...

Day 25 - Exception Handling

首先来认识常见的错误类型: EvalError- eval() 执行错误 RangeError - ...

Gulp 压缩优化程序码(1) DAY88

这里我们先介绍 gulp-clean-css(压缩css) 与 gulp-uglify(压缩js) ...