下面是我的反应功能组件。我每5秒更新一次time状态并显示时间(通过showTime())。
我还拥有一个按钮,当单击该按钮时,它将将当前时间推送到timeList状态(这是一个数组)。
然而,到目前为止,我在handleClick函数中遇到了一个bug。我想要做的是将当前时间推到空的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;发布于 2022-10-14 16:52:01
push返回新的数组长度。您想要的是将time附加到timeList
const handleClick = () => {
if (time) {
const newTimeList = [...timeList, time];
setTimeList(newTimeList);
// or
setTimeList(oldTimeList => ([...oldTimeList, time]));
}
};https://stackoverflow.com/questions/74072299
复制相似问题