【问题标题】:Iterating through JSON and adding to array, but preventing multiple additions to the array遍历 JSON 并添加到数组,但防止多次添加到数组
【发布时间】:2021-12-05 18:58:31
【问题描述】:

遍历 JSON 响应并将 JSON 元素的特定元素插入数组的最佳方法是什么(假设我使用的是 React 挂钩)。这是我的尝试,但问题是我第一次执行该函数时,我没有得到任何输出,第二次,我得到了预期的输出,然后随后的执行继续添加到 datelist 数组中(大小每次翻倍) .

const get = () => {
    fetch('/test')  
        .then(response => response.json())
        .then(data => {setDates(data)})
    setDatelist([]);
    setDatelist(datelist => [...datelist, dates.map(date => date.start["dateTime"])]);
    console.log(datelist);  
}

【问题讨论】:

  • 我通过在运行 map 函数之前将 datelist 重置为空数组来解决加倍的问题。不过,我仍然遇到第一个函数执行没有给我输出的问题。

标签: reactjs react-hooks react-datepicker


【解决方案1】:

我认为您正在寻找的是useEffect 钩子document。它可以订阅 React 状态或 props 更改。

基本上,您的代码应该被分成几个部分,如下所示:

// 1. I assume you have a state to maintain `dates`
const [dates, setDates] = useState([]);

const get = () => {
    fetch('/test')  
        .then(response => response.json())
        .then(data => {setDates(data)}) 
// 2. here you call `setDates` to update the state, from your description it should be working already
}

useEffect(() => {
// 3. in useEffect hook, you can subscribe to `dates` change, and do whatever you need to do here once the dependency is updated
// below is something I copied from your question, please change it based on your need
  setDatelist(datelist => [...datelist, dates.map(date => date.start["dateTime"])]);
  console.log(datelist); 
}, [dates]);

希望对您有所帮助,如果您需要更多信息,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2016-05-24
    • 2018-04-07
    相关资源
    最近更新 更多