【问题标题】:How to initiate React hook state with foreach loop如何使用 foreach 循环启动 React 钩子状态
【发布时间】:2020-11-01 00:41:51
【问题描述】:

抱歉,如果以前可能有人问过这个问题,我不确定是不是这样。我来自 Java 背景,对 React 非常陌生,对这个框架还不是很精通。但我要做的是从一个数组中检索所有数据,以将其设置为通过 useState 启动的另一个数组。我不确定它的语法,因为我尝试通过它的每个循环,但它不会让我。

基本上,我想避免在此处进行这种硬编码,因为我的数据是来自 api 的动态数据:

 const [data, setData] = useState([

        {
            name: reports[0].title,
            runDate: reports[0].runDate,
            createdDate: reports[0].createdDate,
            category: reports[0].category.title,
            actions: 4, 
        },
        {
            name: reports[1].title,
            runDate: reports[1].runDate,
            createdDate: reports[1].createdDate,
            category: reports[1].category.title,
            actions: 4,
        },
    ]
)

非常感谢。

【问题讨论】:

    标签: javascript reactjs react-hooks use-state


    【解决方案1】:

    听起来您只需要可以遍历reports 数组并对其进行转换:

    // pass `reports` into this if you need to
    const getInitialData = () => reports.map(report => ({
      name: report.title,
      runDate: report.runDate,
      createdDate: report.createdDate,
      category: report.category.title,
      actions: 4,
    }));
    
    const [data, setData] = useState(getInitialData);
    

    (我将一个函数传递给useState,因此您只需在装载时将报告转换为所需的数据结构,而不是在每次渲染时)

    【讨论】:

    • 太棒了!非常感谢!那行得通。 :) 我稍后会接受答案,只需要等待几分钟 SO 允许我这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2016-02-15
    • 2019-10-29
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多