我正在使用名为react-countdown-now的包装,我有很多物品,我只是想知道为什么所有物品都同时倒计数
https://codesandbox.io/s/4rpn84j5m0
正如您在下面的示例中看到的那样,新项目保留了旧项目
import React, { Component } from 'react';
import { render } from 'react-dom';
import Countdown from 'react-countdown-now';
class App extends Component {
constructor() {
super();
this.state = {
show: false
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ show: true })
}, 2500)
}
render() {
return (
<div>
<Countdown date={Date.now() + 10000} /><br />
{this.state.show ? <Countdown date={Date.now() + 10000} /> : <span>waiting new item....</span>}
<p>
Why the new item rest the old item?
</p>
</div>
);
}
}
render(<App />, document.getElementById('root'));
为什么新项目保留旧项目?
答案 0 :(得分:1)
原因是因为表达式Date.now() + 10000
在每次重新渲染/状态更新时都会重新计算。您需要将日期存储在某个地方。
例如:
https://codesandbox.io/s/zq1mv4zmz4
import React, { Component } from "react";
import { render } from "react-dom";
import Countdown from "react-countdown-now";
class App extends Component {
constructor() {
super();
this.state = {
dates: [Date.now() + 10000]
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ show: true });
}, 2500);
}
render() {
return (
<div>
{this.state.dates.map(date => (
<div>
<Countdown date={date} />
</div>
))}
<button onClick={() => this.addDate()}>New Item</button>
<p>Why the new item rest the old item?</p>
</div>
);
}
addDate() {
let dates = [...this.state.dates, Date.now() + 10000];
this.setState({ dates });
}
}
render(<App />, document.getElementById("root"));