reactjs 在常量对象中设置属性的动态值

imzjd6km  于 2023-02-04  发布在  React
关注(0)|答案(1)|浏览(165)

我在config.service.ts文件中有这样的常量

export const mysettings={
   userid:"12324",
  conf:{
     sessionDuration:30,
    mac:"LON124"
  }
}

我在某些组件中使用此常量
但是,我需要在运行时从我的公共文件夹中的JSON文件中获取这些值,而不是将它们硬编码到const中
我也有一个这样的函数

async getConfig(){
   const data=await     fetch("./data/data.json")
      .then((response) => response.json())
      .then((json) => return json );

}

因此,在data.json文件中,我有这些常量值,我需要更新JSON文件中的这些值,或者有时替换JSON文件本身。
请帮助我如何实现这一点?

ryevplcw

ryevplcw1#

您可以创建一个Context和ContextProvider来从json文件加载数据,将其设置为状态变量,然后将其传递给Context消费者:
DataContext.tsx:

import { createContext, useState, useContext, useEffect, PropsWithChildren } from "react";
import asyncData from "./asyncData";

interface IData {
  userid: string;
  conf: {
    sessionDuration: number;
    mac: string;
  };
}

interface IContextValue {
  data: IData;
}

const StateContext = createContext<IContextValue>(null!);

export function DataContextProvider(props: PropsWithChildren) {
  const [data, setData] = useState<IData>(undefined!);

  useEffect(() => {
    asyncData.then((json) => setData(json)).catch(console.error);
  }, []);

  // Optionally - wrap with useMemo
  const contextValue: IContextValue = {
    data: data
  };

  return (
    <StateContext.Provider value={contextValue}>
      {data && props.children}
    </StateContext.Provider>
  );
}

export default function useDataContext() {
  const context = useContext(StateContext);
  if (!context) {
    throw new Error(
      "useDataContext must be used within the DataContextProvider"
    );
  }
  return context;
}

更新到索引.tsx:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { DataContextProvider } from "./DataContext";

import App from "./App";
import asyncData from "./asyncData";

asyncData.then((config) => {
  console.log("Config is fetched before render: ", config);

  const rootElement = document.getElementById("root");
  const root = createRoot(rootElement!);

  root.render(
    <StrictMode>
      <DataContextProvider>
        <App />
      </DataContextProvider>
    </StrictMode>
  );
});

用法:

import useDataContext from "./DataContext";

export default function App() {
  const { data } = useDataContext();
  return <div className="App">{JSON.stringify(data)}</div>;
}

asyncData.ts:

const asyncData = fetch("./data/data.json").then((response) => response.json());

export default asyncData;

相关问题