【问题标题】:How to dynamically load a JSON file in React?如何在 React 中动态加载 JSON 文件?
【发布时间】:2020-12-12 22:51:49
【问题描述】:

我需要用大量国家/地区列表填充选择输入。由于国际化,我为每种可用语言都有一个单独的 json 文件。为了不将它们全部加载到我的组件中,我只想导入与当前语言环境对应的那个。

这是我写的:

function MyComponent() {
  const [countries, setCountries] = useState([]);
    const { locale } = useLocale();
  
  useEffect(() => {
    import(`../../data/countries/${locale}.json`)
      .then((res) => setCountries(res.countries))
      .catch(_ => null);
  }, []);
  
  return <Select options={countries}/>
  }

我还想过在单独的文件中编写自己的钩子:

export const useFetchJSON = (file: string) => {
  const [data, setData] = useState({});
  const { locale } = useLocale();
  const res = require(`../data/${file}/${locale}.json`);
  setData(res);
  return data;
};

这些技术都不起作用。如何解决这个问题?谢谢!

【问题讨论】:

  • 你遇到了什么错误?
  • 尝试在catch块内添加console.log

标签: javascript json reactjs import


【解决方案1】:

如果您没有收到任何错误,您可以使用 res.default 获取 json 数据:

 useEffect(() => {
    import(`../../data/countries/${locale}.json`)
      .then((res) => setCountries(res.default.countries))
      .catch(_ => null);
  }, []);

如果您收到此错误:

模块 ./.json 未声明为 System.registerDynamic 的依赖

您应该检查您的模块包配置。

其他解决方案:

1.创建一个对象来存储导入函数

const LocalesData = {
  en_AU: () => import("../../data/countries/en_AU.json"),
  es_ES: () => import("../../data/countries/es_ES.json"),
  //...
};

useEffect(() => {
  LocalesData[locale]()
    .then(res => console.log(res.default))
    .catch(_ => console.log("res", _));
}, []);

2。将静态文件移动到公用文件夹并使用 fetch 加载数据:

  useEffect(() => {
    fetch(`${locale}.json`)
      .then(res => res.json())
      .then(res => console.log(res))
      .catch(_ => console.log(_));
  }, []);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2015-12-22
    • 2018-07-11
    • 2017-10-20
    • 2017-11-21
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多