我有一个包含40个对象的数组,我用forEach循环遍历它们,然后检查当前日期是否等于对象中的日期,如果是,我想得到那些相等的对象,并把它们加到state中。
我现在让它循环,检查日期是否匹配,在if语句中,我只检查日期是否匹配,如果匹配,我用forcast更新state,它应该添加我想要声明的对象,但是它只添加最后一个对state为真的对象,并清除之前的对象,我怎么才能让它添加所有日期匹配的对象呢?
const [todayForcast, setTodayForcast] = useState()
function checkDates() {
const forcastArray = props.forcast.list // Get array containing all forcasts
const date = new Date(); // Get current date
const date1 = date.getDate(); // Get just todays date
// Loop over the array and get each item
forcastArray.forEach(forcast => {
let get_current_dt = forcast.dt_txt // Get d & t from the obj
let split_dt = get_current_dt.split(" ") // Split d & t at the space
let get_full_date = split_dt[0] // Get just the date
let get_date = get_full_date.slice(8) // Remove year & month and get just day
if( get_date == date1){
setTodayForcast(forcast)
}
})
}
3条答案
按热度按时间vi4fp9gy1#
正如Ben提到的,你在每个循环中覆盖了状态。因此,在最后一次forEach迭代结束时,你的状态是最后一次预测的状态。不幸的是,提供的修正解决方案不太正确。我本来想发表评论的,但我的声誉不够高,所以我添加了一个新的答案。
我们需要在循环外初始化一个数组,否则,它将在每次迭代时被覆盖,然后我们又回到原点。例如:
顺便说一句,我不完全确定
forcast.dt_txt
是什么格式,但是您可以简化代码的其余部分:ki1q1bka2#
你现在所做的就是每次把当前的
forcast
设置为状态(应该是forecast
,可能是打字错误,但没关系)。当你设置forcast
时,你会覆盖最后一个状态,如果你想保存所有的状态,你可以做类似的事情。根据Evan的输入,我们创建了一个新的数组
newForecasts
,使用spread...
操作符来扩展newForecasts
中的内容,然后将当前的forcast
添加到其中,也得到了一个添加了当前forcast
的新数组,然后在循环结束后将其设置回todayForcast
状态。avwztpqn3#
你必须使用一个伪数组来推入它,在迭代之后你可以将伪数组设置到状态变量中。希望你得到了...