react hooks redux 在外部js中修改

发布于 2022-09-13 01:10:32 字数 1358 浏览 9 评论 0

root_reducer.jsx

import React, { createContext,useReducer } from 'react';
export const ColorContext = createContext({})

 function reducer(state,action){
    return action
}



export function Load(props){
    const [loadState,dispatch]=useReducer(reducer,false)
    return (
        <ColorContext.Provider value={{loadState,dispatch}}>
            {props.children}
        </ColorContext.Provider>
    )
}

loading.jsx

//todo 自定义遮罩加载状态
import React, { useContext } from 'react'
import { Spin } from 'antd';
import './loading.less'
import { ColorContext} from '../../../reducer/root_reducer.jsx'

function Loadingc(props) {
    const { loadState } = useContext(ColorContext)

    return (
        <>
            {loadState ? (<div className="loading">
                <Spin/>
            </div>) : null}
        </>
    )
}
export default Loadingc

App.jsx

function App() {
      return (
            <Load>
                 <Loadingc></Loadingc>
                  <div className="app">
                  </div>
            </Load>
      )
}
export default App

怎样在独立的http.js中使用dispatch修改状态(或者根据接口请求状态展示‘加载中...’组件),大佬们都是怎么封装'loading'组件的?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聚集的泪 2022-09-20 01:10:32

在线体验地址
关键代码

type MutableRef<T> = {
  current: T;
};

export const createMutableRef = <T>(value: T): MutableRef<T> => {
  return {
    current: value
  };
};

export function GlobalLoadingProvider(props) {
  const [loadState, dispatch] = useReducer(reducer, false);
  dispatchRef.current = dispatch;
  return (
    <ColorContext.Provider value={{ loading: loadState, dispatch }}>
      {props.children}
    </ColorContext.Provider>
  );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文