【发布时间】:2018-10-02 11:48:28
【问题描述】:
因为我需要在react的render中访问indexeddb,所以我使用promise并在render中分离逻辑。
render(){
if(original_flow) dispatch(applyUserAccFilters(groups));
//access indexeddb
else applyShopNameFilters(window,groups).then((
()=>{groupListItems=[];groupListItems.length=0;
//generate UI in groupListItems
//if I change groupListItems to be [], callback's called but empty UI is not rendered
dispatch(genGroupList(groups,groupListItems));
return this.paintUI(groupListItems);}),()=>{}
);
//original flow; this flow can work normally; render of this flow is normal
dispatch(genGroupList(groups,groupListItems));
return this.paintUI(groupListItems);
}
由于我遇到了 react 要求我无论如何都将 return 放在渲染底部的情况,我不禁想知道回调中的任何渲染是否在 react 中是不合法的?
我确实需要在解锁IO的回调中渲染;欢迎任何想法。
【问题讨论】:
-
你没有给我们太多的工作,因为我们不知道这些函数中的任何一个是做什么的,但基础是你会想要在 componentDidMount 生命周期中做你的异步工作钩子,当它完成时调用
this.setState。渲染应该是 state 和 props 的纯函数。 -
React 组件将在其 props 更改或调用
this.setState时调用 render 方法。因此,您可以将异步位移到渲染方法之外,并在其回调或解析中执行这两件事之一。
标签: javascript reactjs promise