遍历 JSON 并添加到数组,但防止多次添加到数组

Iterating through JSON and adding to array, but preventing multiple additions to the array

遍历 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 钩子,document。它可以订阅 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]);

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