【问题标题】:Looping through JSON objects and converting them to React components遍历 JSON 对象并将它们转换为 React 组件
【发布时间】:2022-01-15 06:50:04
【问题描述】:

我有一个JSON 文件,其中包含 3 个不同的对象(card1、card2 和 card3)。 我想遍历JavaScript 中的这些对象,将它们转换为对象的array,然后在我的 React 代码中,我试图根据 JSON 文件中有多少将它们转换为组件。

到目前为止我所拥有的:

import Card from "./card-elements/Card";
import json from "./data.json";

const list = [];
for (const key in json) {
    if (json.hasOwnProperty(key)) {
        list.push(key);
    }
}

function App() {
    return (
        <div className="card-area">
            {list.map(i => {
                return <Card title={i.title}
                             description={i.description}
                             borderColor={"red"}/>
            })}
        </div>
    );
}

export default App;

data.json:

{
    "card1": {
      "title": "Card One",
      "description": "This is card one's description. Straight from JSON file!"
    },
    "card2": {
      "title": "Card Two",
      "description": "Directly from the JSON file, this is card two's description"
    },
    "card3": {
      "title": "Card Three",
      "description": "And finally, this is the last cards description!"
    }
}

电流输出: 我的 React 没有出现错误,它只显示一个组件,并且“标题”和“描述”没有显示

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: javascript reactjs json


    【解决方案1】:

    无需将每个项目推送到list 并使用它。而不是使用Object.entries

    这样试试

    function App() {
        return (
            <div className="card-area">
                {(Object.entries(json) || []).map(([key, value]) => {
                    return (
                        <Card
                            title={value.title}
                            description={value.description}
                            borderColor={"red"}
                        />
                    );
                })}
            </div>
        );
    }
    

    【讨论】:

      【解决方案2】:

      在 React 中,你应该使用 useState 钩子来更新组件。

      Try something like:
      
      import Card from "./card-elements/Card";
      import json from "./data.json";
      
      
      function App() {
          const [cardData, setCardData] = React.useState();
      
          React.useEffect(() => {
            const list = [];
            for (const key in json) {
             if (json.hasOwnProperty(key)) {
                list.push(key);
             }
            }
          }, [])
      
          return (
              <div className="card-area">
                  {cardData && list.map(i => {
                      return <Card title={i.title}
                                   description={i.description}
                                   borderColor={"red"}/>
                  })}
              </div>
          );
      }
      

      导出默认应用;

      【讨论】:

        猜你喜欢
        • 2021-08-15
        • 2019-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2019-11-22
        • 2018-05-20
        • 1970-01-01
        相关资源
        最近更新 更多