下面是我的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;
1条答案
按热度按时间bzzcjhmw1#
push
返回新的数组长度。您需要的是将time
附加到timeList