【Day27】React Redux 原理及应用方法简介 ╰(°ㅂ°)╯

What's Redux !? Redux 是一个用来集中管理state的一个library,

用了Redux我们可以直接取得或修改相同的state,不用再一层一层Component往下传了!


原理

  • 透过一个根Component集中管理states(这个地方通常称为store)
  • store里的states是透过dispatch执行某个action(动作)来进行变化 (一般的states是透过setState来进行变化)
  • dispatch在选择要执行哪一个action的时候,该action会被送到reducer里去决定到底是dispatch哪个action,进而回传新的store

重点

  • 如果有Component要使用store的话,就必须和store连结
  • dispatch action 是回传新的store,而不是直接改变store内的states

在最上层Component镶上Redux和其他Component连结store的方式

  1. 执行以下指令安装redux

    npm install redux
    
  2. 在App.js的地方镶上React Redux 的Provider ,且透过redux的createStore来建立store

    import { createStore } from "redux";
    import reducer from './reducers'
    const store = createStore(reducer)
    
    class App extends React.Component {
      render() {
        return (
          <Provider store={store}>
            <Component />
          </Provider>
        );
      }
    }
    
  3. 上面的程序码我们会看到在建立store的时候需要传入reducer (也就是放置action type 并回传新store的地方),所以我们要建立reducer并传入

    • 开启一个新的js档案
    • 设定要传入reducer的初始states
    • 建立一个function 来决定要回传哪个action里的store (第一个参数为初始值的states,第二个参数为传入的action)
    • 上面有提到说action是用return 的方式去回传store,而不是直接改变state的值
    let initialState;
    
    initialState = {
       aa:""
    };
    
    const reducer = (state = initialState, action) => {
      switch (action.type) {
        case "action1":
           return {
                    ...state,
                    aa:"123"
                };
          break;
        case "action2":
          return {
                    ...state,
                    aa:"333"
                };
          break;
        default:
          return { ...state };
          break;
      }
    
    };
    
  4. 上述程序码,我们在switch里使用到action.type,通常我们会建立一个新的js档案来放置action

    export const action1 = ()=>{
        return {type:'action1'}
    };
    export const action2 = ()=>{
        return {type:'action2'}
    };
    
  5. 在其他Component连结store的方式 (连结state和dispatch)

  • 连结state

    const mapStateToProps = (state) => {
      return { aa: state.aa };
    };
    
  • 连结dispatch

const mapDispatchToProps = (dispatch) => {
  return {
      action1:()=>{dispatch(action1())},
      action2:()=>{dispatch(action2())}
  };
};

以上是Redux的原理及使用方法的补充,

下一篇要来介绍跟Redux作用很像的React Query ,
小菜鸟个人是觉得React Query相对Redux好用满多的 (⊙ꇴ⊙)


<<:  [Angular] Day27. Validating form input

>>:  Day13-React 表单验证篇-使用第三方函式库 Formik 进行表单的验证

Day 10 - 元件的资料传输(2)

昨天我们提到了如何透过元件区分出独立的资料流,但问题来了,如果两个元件的资料需要互通有无呢? 这时候...

【资料结构】图的基本定义

一个图形具有两个集合的基本组成:G(V,E) V:表示顶点的集合 V(G1)={1,2,3,4} E...

英雄列表范例:载入资料

接下来我要用一个小应用来介绍基本的 CRUD 实作:复仇者英雄列表。它的功能如下: 新增英雄到列表中...

Day 47 (Node.js)

1.use static or Router express.static =>Web 服务器...

Day 26.

更新: Bug解掉了,在第28天 今天真的没办法思考.. 还没抓到昨天的错误是为什麽,然後接下来的学...