reactjs 在for循环中向state添加对象只是向state添加最后一个对象

ntjbwcob  于 2022-12-22  发布在  React
关注(0)|答案(3)|浏览(200)

我有一个包含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)
      }
    })
  }
vi4fp9gy

vi4fp9gy1#

正如Ben提到的,你在每个循环中覆盖了状态。因此,在最后一次forEach迭代结束时,你的状态是最后一次预测的状态。不幸的是,提供的修正解决方案不太正确。我本来想发表评论的,但我的声誉不够高,所以我添加了一个新的答案。
我们需要在循环外初始化一个数组,否则,它将在每次迭代时被覆盖,然后我们又回到原点。例如:

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
    
    // We need to initialize the array outside of the loop, otherwise it gets overwritten
    // each iteration and we're back at square one.
    const newForecasts = []; 

    // 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){

        // Append the current forcast to the newForescasts array defined earlier
        newForecasts.push(forcast);
      }
    })

    // After the loop is finished, set the state to the newForecasts
    setTodayForcast(newForecasts)
  }

顺便说一句,我不完全确定forcast.dt_txt是什么格式,但是您可以简化代码的其余部分:

const [todayForcast, setTodayForcast] = useState()
  function checkDates({ forcast }) {
    const forcastArray = forcast.list
    const date = new Date().getDate()
 
    const newForecasts = []

    forcastArray.forEach(f => {if (date == new Date(f.dt_txt).getDate()) newForecasts.push(f))}
    setTodayForcast(newForecasts)
  }
ki1q1bka

ki1q1bka2#

你现在所做的就是每次把当前的forcast设置为状态(应该是forecast,可能是打字错误,但没关系)。当你设置forcast时,你会覆盖最后一个状态,如果你想保存所有的状态,你可以做类似的事情。

// chose an array, maybe you want an object instead at the beginning
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
  let newForecasts = [];
  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){
      // make a new array (or object) and add the new forcast to it
      newForecasts = [...newForecast, forcast];
    }
  })
  setTodayForcast(newForecasts);
}

根据Evan的输入,我们创建了一个新的数组newForecasts,使用spread ...操作符来扩展newForecasts中的内容,然后将当前的forcast添加到其中,也得到了一个添加了当前forcast的新数组,然后在循环结束后将其设置回todayForcast状态。

avwztpqn

avwztpqn3#

你必须使用一个伪数组来推入它,在迭代之后你可以将伪数组设置到状态变量中。希望你得到了...

相关问题