简体   繁体   English

setTimeout 中的多个状态更新

[英]Multiple state update in setTimeout

import { useEffect, useState } from "react";

export default function App() {
  const [criteria, setCriteria] = useState({});

  const handleCriteriaChange = (values) => {
    // setCriteria(prevCriteria => ({
    //   ...prevCriteria,
    //   ...values
    // }))
    setCriteria({
      ...criteria,
      ...values
    });
  };

  useEffect(() => {
    setTimeout(() => {
      handleCriteriaChange({
        courses: ["calculus", "psychology"]
      });
    }, 1000);

    setTimeout(() => {
      handleCriteriaChange({
        type: "manual"
      });
    }, 5000);

    setTimeout(() => {
      handleCriteriaChange({
        termLengths: [14, 7]
      });
    }, 10000);
    // eslint-disable-next-line
  }, []);

  console.log({ criteria: JSON.stringify(criteria) });
  return (
    <div className="App">
      <h1>Hello CodeSandbox {JSON.stringify(criteria)}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I've added a logic to update state object with different keys in 5 seconds gap between each update.我添加了一个逻辑来在每次更新之间的 5 秒间隔内使用不同的键更新状态对象。 And I was expecting all key values appear in the state object, but only the last state update is displaying.我期待所有键值都出现在状态对象中,但只显示最后一次状态更新。 Why I can't get all the added key: values?为什么我无法获得所有添加的键:值? Even if there's a state batching they are updating state with different keys.即使有状态批处理,它们也会使用不同的键更新状态。

the issue with your update state function handleCriteriaChange .您的更新状态函数handleCriteriaChange variable criteria is empty in useEffect function and when you use it or assign it.useEffect函数中以及当您使用或分配它时,变量criteria为空。 you have to use the previous state value while updating the state.您必须在更新状态时使用先前的状态值。

import React from 'react';

import { useEffect, useState } from 'react';

export default function App() {
  const [criteria, setCriteria] = useState({});

  const handleCriteriaChange = (values) => {
   
    setCriteria(prev=> ({
      ...prev,
      ...values,
    }));
  };

  useEffect(() => {
    setTimeout(() => {
      handleCriteriaChange({
        courses: ['calculus', 'psychology'],
      });
    }, 1000);

    setTimeout(() => {
      handleCriteriaChange({
        type: 'manual',
      });
    }, 5000);

    setTimeout(() => {
      handleCriteriaChange({
        termLengths: [14, 7],
      });
    }, 10000);
    // eslint-disable-next-line
  }, []);

  console.log({ criteria: JSON.stringify(criteria) });
  return (
    <div className="App">
      <h1>Hello CodeSandbox {JSON.stringify(criteria)}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM