通过JSON循环并添加到数组中,但防止多次添加到数组



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

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);  
}

我想您要找的是useEffect挂钩,文档。它可以订阅React状态或道具更改。

从本质上讲,您的代码应该分为几个部分,类似于以下内容:

// 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]);

希望这能有所帮助,如果你需要更多信息,请评论。

最新更新