【问题标题】:Fill context from REST API and use it in a React component with useEffect and useContext从 REST API 填充上下文并在带有 useEffect 和 useContext 的 React 组件中使用它
【发布时间】:2020-06-12 13:02:31
【问题描述】:

先决条件

我在一个带有一些输入的组件中有一个表单,这些输入需要一些配置数据。配置数据来自 REST API。

目标

调用 REST API 并将配置数据存储在 React 上下文中,以便重复使用。

做了什么

1/ 我创建了组件及其输入。 2/ 我使用模拟配置数据来渲染组件。 3/ 我创建了上下文,所以我用 React 上下文提供的一组新配置数据替换了模拟配置数据(总是模拟)。 4/ 我用来自 REST API 的配置数据填充了上下文。

问题

我在组件中使用上下文 API,但从上下文返回的配置数据为空。

interface ContextType {
  formConfig: any[];
}

export const Context = React.createContext<ContextType>({
 formConfig: [],
 getFormConfig: () => [],
});


export const ContextProvider: React.FC<{
  children: React.ReactNode;
}> = ({ children }) => {

  let formConfig: any[] = [];

  function getFormConfig() {
    return formConfig;
  }

  useEffect(() => {
    (async function fetchData() {
      formConfig = await ServiceConfig.getFormTypes();
      console.log(formConfig, 'use effect of context'); // It shows the conf
    })();
  }, []);


  return (
    <Context.Provider
      value={{
        getFormConfig,
        formConfig
      }}
    >
      {children}
    </Context.Provider>
  );
};

const FormUI: React.FC = () => {


    const { getFormConfig } = useContext(Context);

    useEffect(() => {
        console.log(getFormConfig(), 'form'); // it is empty here
    }, []);

    return (
        <ContextProvider>
            ....
        </ContextProvider>
    )
};

【问题讨论】:

    标签: reactjs rest react-hooks react-context use-effect


    【解决方案1】:

    let formConfig: any[] = [];只是一个变量,当你重新渲染它时,它会被重新创建并分配[]给它。

    你需要将它存储在一个状态中。

    const [formConfig, setFormConfig] = React.useState([])
    

    在异步函数中,你设置状态

      useEffect(() => {
        (async function fetchData() {
          formConfig = await ServiceConfig.getFormTypes();
          setFormConfig(formConfig) // setting the state
          console.log(formConfig, 'use effect of context'); // It shows the conf
        })();
      }, []);
    

    很抱歉无法在打字稿中给你答案

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2020-02-02
      • 2020-05-29
      • 2021-07-06
      • 2017-05-07
      • 2020-08-19
      • 2022-09-06
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多