javascript - react : update component after an async event not connect to the component

标签 javascript asynchronous reactjs

在我的应用程序中,我有一个依赖于状态的组件,该组件将在组件内部未处理的异步事件发生后更新。

var Status = React.createClass({
    getInitialState: function () {
        return {
            state: 'loading'
        };
    },
    render: function () {
        return React.createElement('span', null, this.state.state);
    }
});

var status = React.createElement(Status);
React.render(status, mountNode);

我希望能够做这样的事情:

doAsyncThing(function callback() {
    status.setState({ state: 'done' });
});

我知道异步逻辑可以移动到componentDidMount,如图here , 但是否可以将其移出组件?还是将这样的逻辑放在组件中只是 React zen?

最佳答案

Pubsub 模式可能是您的解决方案(在本例中使用 Backbone):

var ps=_.extend({},Backbone.Events);
var Status = React.createClass({
    getInitialState: function () {
        return {
            state: 'loading'
        };
    },
    componentDidMount: function(){
       ps.on('done',function(){
            status.setState({ state: 'done' });
       });//your callback function
    },
    render: function () {
        return React.createElement('span', null, this.state.state);
    }
});

var status = React.createElement(Status);
React.render(status, mountNode);

然后在doAsyncThing回调中触发done事件:

doAsyncThing(function callback() {
    ps.trigger('done');
});

关于javascript - react : update component after an async event not connect to the component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32062936/

相关文章:

javascript - 使用 Angular 或 Jquery 的 DOM 操作?

javascript - 如何减少 javascript 的加载时间?

javascript - 工厂内 promise , promise 完成前返回

node.js - 我应该发送多少个并发 http 请求?

javascript - 如何避免 UI5 中的 "Synchronous XMLHttpRequest on the main thread"警告?

c# - ConfigureAwait(false) 仍然死锁

javascript - 如何在给定单词列表的情况下找到唯一词缀列表?

javascript - 如何从一组数组中获取所有组合

javascript - 如何正确制作垂直可滚动区域

reactjs - 单独的 Axios 调用数组中的每个项目