react整合原生redux(一)

项目创建

create-react-app reduxdemo

依赖包

yarn add redux -s

思路

  1. 通过redux创建全局唯一store
  2. 通过store获取所需数据
  3. 通过dispatch分发action对象引起store的state改变
  4. 通过store的subscribe改变视图层

src文件目录

|-app.js
|-store.js
|-index.js

删减index.js

通过create-react-app创建的项目有许多无用的东西,首先将src目录清理如上文件内容,然后将index.js精简如下

// index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./app";

ReactDOM.render(<App />, document.getElementById("root"));

创建store

store.js是redux的核心文件,本文用于学习,不强调代码细拆分,故reducer和store写在一起

// store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension"; //chrome redux调试工具

// state初始值
const initState = {
  list: ["a", "b"]
};

// reducer格式
const reducer = (state = initState, action) => {
  const { type, payload } = action;
  // action的type处理
  if (type === "SAVE") {
    return Object.assign({}, state, payload);
  }
  return state;
};

/**
 * 实例化store
 * 参数1: reducer
 * 参数2: 中间件
 */
export default createStore(reducer, composeWithDevTools(applyMiddleware()));

应用代码app.js

// app.js
import React, { useState, useEffect } from "react";
import store from "./store";

export default () => {
  // 获取store中的state,并放进hook函数,类似this.setState(store.getState())
  const [state, setState] = useState(store.getState());
  useEffect(() => {
    // store订阅函数,当state通过store.dispatch分发action改变时此函数自动执行
    store.subscribe(() => {
      setState(store.getState()); //重新设置组件state的值,使视图更新
    });
  }, []); // []表示只执行一次

  const { list } = state;

  const addList = () => {
    list.push(Date.now());
    store.dispatch({ type: "SAVE", payload: { list } }); //分发一个action对象
  };

  return (
    <div>
      <button onClick={addList}>add</button>
      <ul>
        {list.map(v => {
          return <li key={v}>{v}</li>;
        })}
      </ul>
    </div>
  );
};

action对象格式为json对象,并且必须有type属性否则会报错误:Error: Actions may not have an undefined "type" property. Have you misspelled a constant?

携带数据一般为payload属性,这个没做强制要求

这样一个基本的react redux就整合完成了,查看完整代码

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注