Flux/Alt-setTimeout未更新存储

Flux/Alt setTimeout not updating store

本文关键字:更新 存储 Alt-setTimeout Flux      更新时间:2023-09-26

我正试图使用Alt.在我的React应用程序中创建一个类似"Toast"的基本服务

我已经完成了大部分逻辑,我可以在触发add(options)操作时将新项目添加到阵列中,这些项目会出现在我的视图中,但我也试图允许发送超时,并在toast项目启动后删除它:

onAdd(options) {
    this.toasts.push(options);
    const key = this.toasts.length - 1;
    if (options.timeout) {
        options.timeout = window.setTimeout(() => {
            this.toasts.splice(key, 1);
        }, options.timeout);
    }
}

此外,toast会出现在我的页面上,超时也会被触发(比如几秒钟后),但在setTimeout内部操纵this.toasts似乎没有任何效果。

显然,这缺少了核心功能,但除了setTimeout部分之外,一切都正常工作。

超时似乎是在内部设置状态,而不是广播更改事件。它可能和调用forceUpdate()一样简单。但我使用的模式是调用setState(),我认为在这种情况下您可能想要这样做。

以下是更新状态和广播更改事件的示例。

import alt from '../alt'
import React from 'react/addons'
import ToastActions from '../actions/ToastActions'
class ToastStore {
	constructor() {
		this.toasts = [];
		this.bindAction(ToastActions.ADD, this.add);
		this.bindAction(ToastActions.REMOVE, this.remove);
	}
	add(options) {
		this.toasts.push(options);
		this.setState({toasts: this.toasts});
		if (options.timeout) {
			// queue the removal of this options
			ToastActions.remove.defer(options);
		}
	}
	remove(options) {
		const removeOptions = () => {
			const toasts = this.toasts.filter(t => t !== options);
			this.setState({toasts: toasts});
		};
		if (options.timeout) {
			setTimeout(removeOptions, options.timeout);
		} else {
			removeOptions();
		}
	}
}
module.exports = alt.createStore(ToastStore, 'ToastStore');