Reaction功能组件:更新状态的onClick处理程序不工作

wbgh16ku  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(156)

下面是我的Reaction功能组件。每隔5秒,我就会更新time状态并显示时间(通过showTime())。
我还有一个按钮,当单击该按钮时,会将当前时间推送到timeList状态(这是一个数组)。
然而,到目前为止,我在handleClick函数中得到了一个错误。我希望发生的是将当前时间压入空的timeList数组(timeList.push(time))。所以timeList应该是这样的:[‘12:34:57’]。然而,当按钮被按下时,timeList变成了1

import React, {useState, useEffect} from 'react';

function App() {
  const [time, setTime] = useState(null);
  const [timeList, setTimeList] = useState([]);

  useEffect(
    () => {
      calcTime();
    }, [time]
  );

  const calcTime = () => {
    setTimeout(
      () => {
        const today = new Date();
        const timeNow = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
        setTime(timeNow);
      }, 5000
    );
  };

  const showTime = () => {
    if (time) {
      return <p>{time}</p>
    } else {
      return <p>No time yet</p>
    }
  };

  const handleClick = () => {
    if (time) {
      const newTimeList = timeList.push(time);
      console.log(newTimeList); // first time the button is pushed "1" is logged here
      setTimeList(newTimeList);
    }
  };

  const showTimeList = () => {
    if (timeList.length) {
      const timesArr = timeList.map((item) => {
        return <p>item</p>
      });
      return timesArr;
    } else {
      return <p>Time list will go here</p>
    }
  };

  return (
    <div className="App">
      {showTime()}
      {showTimeList()}
      <button onClick={handleClick}>Add this time to the time list</button>
    </div>
  );
}

export default App;
bzzcjhmw

bzzcjhmw1#

push返回新的数组长度。您需要的是将time附加到timeList

const handleClick = () => {
    if (time) {
      const newTimeList = [...timeList, time];
      setTimeList(newTimeList);
      // or
      setTimeList(oldTimeList => ([...oldTimeList, time]));
    }
  };

相关问题