如何从存储中读取配置以在 react-admin 中为 DataProvider 提供 url

How to read a config from storage to provide url for DataProvider inside react-admin

我添加了 react admin in a sample project, in dataProvider I use simpleRestProvider,它是用 httpClient 和 apiHost 初始化的,一切都按预期工作,但我想从在索引中获取并设置到商店中的配置文件中获取 apiHost

index.tsx

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('content'),
    () => config
            .fetchConfig()//after fetch is saved in store
            .catch(console.error('error', '[App]'))
);

App.tsx

 <Admin
        dataProvider={dataProvider}
        authProvider={authProvider}
        dashboard={Dashboard}
         ....
</Admin>

dataProvider.ts

//const apiHost = "https://example.com"
const apiHost = store.getState().config.apiHost;

const httpClient = async (url, options = {}) => {
...
return fetchUtils.fetchJson(url, options);
};

const dataProvider = simpleRestProvider(apiHost, httpClient);
export default dataProvider;

on init store.getState().config.apiHost return 错误,因为配置未定义

ReactDom.render() 的第三个参数在 组件安装后 执行 (source)。这就是问题所在:您首先呈现应用程序(并初始化 dataProvider),然后设置配置。

要更早地设置配置,您必须围绕 react-admin 应用程序创建一个包装器组件来获取您的配置,并且仅在收到配置后安装该应用程序。

类似于:

const AppWrapper = () => {
   const [configFetched, setConfigFetched] = useState(false); 
   useEffect(() => {
      config
         .fetchConfig()//after fetch is saved in store
         .then(() => setConfigFetched(true))
         .catch(console.error('error', '[App]'));
    }, []);
    return configFetched ? <App /> : null;
}