react-redux简单使用

react-redux 简单使用步骤

一、创建 action

1. action 实质上是一个包含type属性的Object对象
2. 它的作用只是告诉reducer要做什么,小老板之类的

二、创建 reducer

1. 接收action传过来的命令
2. 按照命令修改state仓库(打工人)

三、创建 store

1. 赋予reducer权限,让其有权限修改仓库

四、关联到 jsx 上 --> Provider

1. 使用Provider的store属性将store关联到jsx上
2. 保证全局只有一个store

五、jsx 中发送数据

1. 导入actions
2. 导入dispatch
3. 在需要的地方使用dispatch发送actions

六、jsx 中接收数据

1. 使用useSelector获取想要的数据
2. enjoy

示例代码

一、创建 action

export const addOne = {
  type: "add_one",
};

export const reduceOne = {
  type: "reduce_one",
};

二、创建 reducer

const initState = {
  count: 0,
};
const reducer = (state = initState, action) => {
  const { type } = action;
  switch (type) {
    case "add_one":
      return {
        count: state.count + 1,
      };
    case "reduce_one":
      return {
        count: state.count - 1,
      };
    default:
      return state;
  }
};

export default reducer;

三、创建 store

import { createStore } from "redux";

import reducer from "../reducer";

// store
export default createStore(reducer);

四、关联到 jsx 上 --> Provider

import React from "react";
import { Provider } from "react-redux";

import store from "./store";
import ComA from "./pages/ComA";
import ComB from "./pages/ComB";

export default function App() {
  return (
    <Provider store={store}>
      <ComA />
      <ComB />
    </Provider>
  );
}

五、jsx 中发送数据

import { useDispatch } from "react-redux";
import * as actions from "../../action";

const addOne = (dispatch) => {
  dispatch(actions.addOne);
};

const reduceOne = (dispatch) => {
  dispatch(actions.reduceOne);
};

const ComA = (props) => {
  const dispatch = useDispatch();
  return (
    <>
      <button onClick={() => addOne(dispatch)}>+</button>
      <button onClick={() => reduceOne(dispatch)}>-</button>
    </>
  );
};

export default ComA;

六、jsx 中接收数据

import { useSelector, shallowEqual } from "react-redux";

const ComB = () => {
  const data = useSelector((state) => {
    return state.count;
  }, shallowEqual);
  return <div>{data}</div>;
};

export default ComB;

shallowEqual 用于比较状态是否发生改变,如果这个函数的执行结果为 false 就表示状态发生改变,组件将重新渲染。

原文地址:https://www.cnblogs.com/selfdef/p/13932753.html