【问题标题】:How to render in promise's resolve如何呈现承诺的决心
【发布时间】: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


【解决方案1】:

根据问题中可用的上下文,我的答案是:

  • 几乎总是,您不想在 render 方法中执行任何异步操作。
  • React 提供了一组生命周期方法来解决这个问题。在您的情况下,根据您希望何时执行异步方法,您将使用以下内容:
    1. ComponentDidMount(如果您希望您的方法在 React 加载相应的组件后立即执行)
    2. ShouldComponentUpdate 中指定更新规则并在ComponentDidUpdate 中执行您的异步函数;如果您有需要通过异步方法处理的“实时”数据。

在您的异步函数中,使用this.setState({key: value}) 模式将异步函数的结果设置为状态。在您的 render 方法中,您应该使用相应的状态变量。这是理想的、健康的 React 编码方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2014-01-04
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多