【发布时间】:2021-05-18 10:19:18
【问题描述】:
我正在制作秒表,当我想第二次重置时钟时,它没有改变。 第一次点击设置h:0,m:0,s:0,再次点击不设置h:0,m:0,s:0,秒表继续。
const events$ = merge(
fromEvent(startBtn, 'click').pipe(mapTo({count: true})),
click$.pipe(mapTo({count: false})),
fromEvent(resetBtn, 'click').pipe(mapTo({time: {h: 0, m: 0, s: 0}})) // there is reseting
)
const stopWatch$ = events$.pipe(
startWith({count: false, time: {h: 0, m: 0, s: 0}}),
scan((state, curr) => (Object.assign(Object.assign({}, state), curr)), {}),
switchMap((state) => state.count
? interval(1000)
.pipe(
tap(_ => {
if (state.time.s > 59) {
state.time.s = 0
state.time.m++
}
if (state.time.s > 59) {
state.time.s = 0
state.time.h++
}
const {h, m, s} = state.time
secondsField.innerHTML = s + 1
minuitesField.innerHTML = m
hours.innerHTML = h
state.time.s++
}),
)
: EMPTY)
stopWatch$.subscribe()
【问题讨论】:
-
我怀疑这种情况正在发生,因为您每次调用
mapTo()时都使用相同的对象实例。尝试使用map(() => ({time: {h: 0, m: 0, s: 0}}))instad。 -
@martin 很好用,非常感谢
标签: rxjs rxjs-observables rxjs-pipeable-operators