React hook Redux usereducer usecontext enables Redux to be accessed from external JS

Time:2021-11-24

Create master file

  1. root directorysrcestablishreducerfolder
  2. Create under folderuseDataX.jsfile
//useDataX.js

import { createContext, useContext, useReducer } from "react";

//?  Thrown to create a context that can be accessed (via the value of DataContext. Provider)
export const DataContext = createContext({});

//?  Define initial value (used to create usereducer)
const creatData = {
  loading:false
}

//?  Thrown, the method can be accessed in ordinary JS
export function dispatchRef(value){
    return {
      current: value
    };
}

//?  This form is called reducer (the value transmitted through usereducer, receiving state: original value (after changing createdata), action: changed value (the value transmitted from dispatch)
function reducer(state, action) {
  if(action.type==='loading'){
    Let stateclone = {... State} // deep copy copy is required here. You can use json.parse (JSON. Stringify (state)) to convert it
    stateClone.loading=action.value
    return stateClone
  }
}

//?  Thrown to get the value in the DataContext
export function useData(){
  const { Xdata } = useContext(DataContext);
  return Xdata;
};

//Main function (can wrap root component)
export function GlobalLoadingProvider(props) {
  //Todo usereducer accepts a reducer function as a parameter, and reducer accepts two parameters, one is state and the other is action.
  //Todo then returns a status count and dispath. Count is the value in the returned status, and dispatch is a that can publish events to update the state.
  //?  Update dataarr after modifying dispath!
  const [dataArr, dispatch] = useReducer(reducer, creatData);
  //?  Access in normal JS
  dispatchRef.current = dispatch;
  return (
    <DataContext.Provider value={{ Xdata: dataArr, dispatch }}>
      {props.children}
    </DataContext.Provider>
  );
}

use

  1. index.jsAdd package label to main entry file<GlobalLoadingProvider></GlobalLoadingProvider>
//index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App.jsx";
// import reportWebVitals from './reportWebVitals';
import { GlobalLoadingProvider } from "./reducer/useDataX";
ReactDOM.render(
  <React.StrictMode>
    <GlobalLoadingProvider>
      <App />
    </GlobalLoadingProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
  1. get data
import { useData } from "./reducer/useDataX";
function Test() {
  const { loading } = useData();
  return <div>{loading}</div>;
}
export default Test;
  1. Modify data in component
import React, { useContext } from "react";

import { DataContext } from "./reducer/useDataX";
function Test() {
  const { dispatch } = useContext(DataContext);
  return (
    <div>
      <button
        onClick={() => {
          dispatch({ type: "loading", value: true });
        }}
      >
        load
      </button>
    </div>
  );
}
export default Test;
  1. Common JS modify data
import { dispatchRef } from "../reducer/useDataX";
dispatchRef.current({type:'loading',value:true});

end

That’s it. Pay attention to whether the path is correct when referencing. Now the main files are written together, and some encapsulation can be done after the business logic is complex.

Recommended Today

Seven solutions for distributed transactions

1、 What is distributed transaction Distributed transaction means that transaction participants, transaction supporting servers, resource servers and transaction managers are located on different nodes of different distributed systems. A large operation is completed by more than n small operations. These small operations are distributed on different services. For these operations, either all of them are […]