Flux / Alt setTimeout未更新商店

时间:2015-11-13 15:24:54

标签: javascript reactjs toast reactjs-flux

我试图创建一个基本的" Toast"喜欢使用Alt在我的React应用中提供服务。

我已经掌握了大部分逻辑,我可以在触发add(options)操作时在我的视图中添加新项目,但是我还尝试允许超时发送后删除一个吐司项目:

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会出现在我的页面上,并且超时也会被触发(比如几秒钟后),但是在this.toasts内部操纵setTimeout似乎没有任何效果

显然这是缺少核心功能,但一切都与setTimeout部分不同。

1 个答案:

答案 0 :(得分:0)

似乎超时是在内部设置状态而不是广播更改事件。它可能就像调用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');

相关问题