在ReactJS中动态加载JSON文件

huangapple go评论65阅读模式
英文:

Dynamically load json file in ReactJS

问题

以下是您要翻译的部分:

"I'd like to load a json dynamically with ReactJS.
Here's my component codes. When the user selects an id, I want to print its information according to selected id which stores at each json file.
But, as below comments, assigning imported value into the imported_json doesn't work. How can I synchronously assign the values and renders imported_json after that?

import React from 'react';
import { useState } from 'react';

export default function Dashboard() {
  const [selected, setSelected] = useState("");
  let imported_json;

  const handleSelect = (item: any) => {
    setSelected(item);
    const jsonPath = `./json/${selected}.json`;
    import(`${jsonPath}`).then((jsonFile) => {
      console.log(jsonFile); // it correctly prints json file.
      imported_json = jsonFile;
    });
  };

  console.log(imported_json); // imported_json prints undefined.

  return (
    <>

    <div>
      <Select label="Select id" onChange={handleSelect}>
        <Option value="1">1</Option>
        <Option value="2">2</Option>
        <Option value="3">3</Option>
      </Select>
    </div>
    <div>
      {imported_json.modelName}
    </div>

    </>
  );
}

And json file looks like below.

{
  "modelName" : "my_model"
}
英文:

I'd like to load a json dynamically with ReactJS.

Here's my component codes. When the user selects an id, I want to print its information according to selected id which stores at each json file.

But, as below comments, assigning imported value into the imported_json doesn't work. How can I synchronously assign the values and renders imported_json after that?

import React from &#39;react&#39;;
import { useState } from &#39;react&#39;;

export default function Dashboard() {
  const [selected, setSelected] = useState(&quot;&quot;);
  let imported_json;

  const handleSelect = (item: any) =&gt; {
    setSelected(item);
    const jsonPath = `./json/${selected}.json`;
    import(`${jsonPath}`).then((jsonFile) =&gt; {
      console.log(jsonFile); // it correctly prints json file.
      imported_json = jsonFile;
    });
  };

  console.log(imported_json); // imported_json prints undefined.

  return (
    &lt;&gt;

    &lt;div&gt;
      &lt;Select label=&quot;Select id&quot; onChange={handleSelect}&gt;
        &lt;Option value=&quot;1&quot;&gt;1&lt;/Option&gt;
        &lt;Option value=&quot;2&quot;&gt;2&lt;/Option&gt;
        &lt;Option value=&quot;3&quot;&gt;3&lt;/Option&gt;
      &lt;/Select&gt;
    &lt;/div&gt;
    &lt;div&gt;
      {imported_json.modelName}
    &lt;/div&gt;

    &lt;/&gt;
  );
}

And json file looks like below.

{
  &quot;modelName&quot; : &quot;my_model&quot;
}

答案1

得分: 1

这是您提供的代码的翻译:

import React from "react";
import { useState, useCallback } from "react";

export default function Dashboard() {
  const [json, setJson] = useState(undefined); // 为 JSON 添加状态
  const [selected, setSelected] = useState("");

  // 将函数设为异步,并使用 useCallback 包装以避免不必要的重新渲染
  const handleSelect = useCallback(async (item: any) => {
    const value = (await import(`./json/${item}.json`)).default;
    setSelected(item);
    setJson(value);
  }, []);

  // 添加条件渲染以避免在 JSON 未定义时出错
  return (
    <>
      <div>
        <Select label="选择 ID" onChange={handleSelect}>
          <Option value="1">1</Option>
          <Option value="2">2</Option>
          <Option value="3">3</Option>
        </Select>
      </div>

      {!!json && <div>{json.modelName}</div>}
    </>
  );
}

希望这有所帮助!如果您有其他问题或需要进一步的帮助,请随时提问。

英文:

Well, you can try to add another state for your json file, in this case, i supose, you will see name of the file, because when you use local variable (let imported_json), react doesn`t re-render your page when you change it, but when you change the state, React will re-render your page. Here is a slightly modified version of your code:

import React from &quot;react&quot;;
import { useState, useCallback } from &quot;react&quot;;

export default function Dashboard() {
  const [json, setJson] = useState(undefined); // add state for json
  const [selected, setSelected] = useState(&quot;&quot;);

  // make function async and wrap in useCallback to avoid unnecessary re-renders
  const handleSelect = useCallback(async (item: any) =&gt; {
    const value = (await import(`./json/${item}.json`)).default;
    setSelected(item);
    setJson(value);
  }, []);

  // added conditional rendering to avoid error when json is undefined
  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;Select label=&quot;Select id&quot; onChange={handleSelect}&gt;
          &lt;Option value=&quot;1&quot;&gt;1&lt;/Option&gt;
          &lt;Option value=&quot;2&quot;&gt;2&lt;/Option&gt;
          &lt;Option value=&quot;3&quot;&gt;3&lt;/Option&gt;
        &lt;/Select&gt;
      &lt;/div&gt;

      {!!json &amp;&amp; &lt;div&gt;{json.modelName}&lt;/div&gt;}
    &lt;/&gt;
  );
}

huangapple
  • 本文由 发表于 2023年5月22日 16:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定