react hooks redux 在外部js中修改

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'组件的?

阅读 1.9k
1 个回答

在线体验地址
关键代码

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>
  );
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题