【问题标题】:How to share data from Provider to function react如何从 Provider 共享数据到函数 react
【发布时间】:2022-09-27 09:57:59
【问题描述】:

我创建了一个共享多个 util 函数的 NPM 库。其中之一是调用我们的端点。我已经在我的 NPM 库中包含了 Axios,但我无法在全局范围内设置 Axios.create 实例。

我最初以为我可以创建一个Provider 并设置一个context,但是,由于我的API 函数不在挂钩中,我无法访问上下文。这是我第一个不熟悉最佳实践的 NPM 库。

// Provider.ts

export default function Provider({ children, config }: ProviderProps) {
  window.config = config;
  return (
    <ContextConfig.Provider value={config}>{children}</ContextConfig.Provider>
  );
}

^ 以上,我尝试使用上下文 API,设置全局变量等。

// api.ts

import Axios, { AxiosInstance, AxiosPromise, Cancel } from \'axios\';

const axiosInstance = Axios.create(window.config);

const api = (axios: AxiosInstance) => ({
  get: <T>(url: string, config: ApiRequestConfig = {}) =>
    withLogger<T>(withAbort<T>(axios.get)(url, config)),
});

export default api(axiosInstance)

^ 上面,尝试使用全局变量window.config,然而,它是undefined。还尝试将导出转换为钩子以允许读取上下文,但是,在不安全地使用钩子时出现错误。

// index.ts

import api from \'./api\';
import Provider from \'./Provider\';

export { api, Provider };

我现在可以考虑处理这个问题的唯一方法是使用本地存储,非常愿意提供建议。

干杯

    标签: javascript reactjs typescript npm axios


    【解决方案1】:

    除了 Axios 实例之外,您是否需要任何配置?

    为什么不直接创建一个 Provider / Context 设置来为您处理您的 api 对象?

    // Create a context for the api
    const ApiContext = createContext({});
    
    // Create a Provider component.
    const ApiProvider = ({ config }) => {
    
        // recreate the api every time the provided configuration changes.
        const api = useMemo(() => {
            // create axios instance using the provided config.
            const axiosInstance = Axios.create(config);
    
            // create API object
            return {
                get: <T,>(url: string, apiConfig: ApiRequestConfig = {}) => withLogger<T>(withAbort<T>(axiosInstance.get)(url, apiConfig))
            };
        }, [config] /* dependency array - determines when api will be recomputed */)
    
        return (
            <ApiContext.Provider value={api}>
                {children}
            </ApiContext.Provider>
        );
    };
    
    const useApi = () => {
        // retrieve configured API from context.
        const api = useContext(ApiContext);
    
        return api;
    }
    
    // Example component to show how to retrieve api for use.
    const Example = () => {
        // retrieve configured API from context.
        const api = useContext(ApiContext);
    
        //OR
    
        const api = useApi();
    
        // use api here
    
        return (
            <div>
                Content goes here
            </div>
        )
    }
    
    // App component to show providing config for API.
    const App = () => {
    
        // Create config (should only update reference when values need to change)
        const config = useMemo(() => ({
            // add config here
        }), []);
    
        return (
            // pass config to API Provider.
            <ApiProvider  config={config}>
                <Example />
            </ApiProvider>
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 2014-03-21
      • 2011-02-02
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多