在我的应用程序中,我有一个依赖于状态的组件,该组件将在组件内部未处理的异步事件发生后更新。
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/