首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >:更新状态的onClick处理程序不工作

:更新状态的onClick处理程序不工作
EN

Stack Overflow用户
提问于 2022-10-14 16:42:49
回答 1查看 19关注 0票数 0

下面是我的反应功能组件。我每5秒更新一次time状态并显示时间(通过showTime())。

我还拥有一个按钮,当单击该按钮时,它将将当前时间推送到timeList状态(这是一个数组)。

然而,到目前为止,我在handleClick函数中遇到了一个bug。我想要做的是将当前时间推到空的timeList数组(timeList.push(time))上。所以timeList是这样的:'12:34:57‘。然而,当按下按钮时,timeList却是1

代码语言:javascript
运行
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-14 16:52:01

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

代码语言:javascript
运行
复制
const handleClick = () => {
    if (time) {
      const newTimeList = [...timeList, time];
      setTimeList(newTimeList);
      // or
      setTimeList(oldTimeList => ([...oldTimeList, time]));
    }
  };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74072299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档