代码之家  ›  专栏  ›  技术社区  ›  pramesh

在redux返回结果之前如何处理render方法?

  •  3
  • pramesh  · 技术社区  · 6 年前

    componentWillMount 方法来设置redux状态。我需要处理 render 方法,直到将这些结果重新复制到道具。这需要一些时间。由于数据不可用,渲染方法此时将失败。我试过设置 default state 但从那以后就不管用了 redux state 将映射到具有 mapStateToProps

    提前谢谢

    5 回复  |  直到 6 年前
        1
  •  0
  •   Ehsan Korhani    6 年前

    通常,当数据不存在时,您将呈现不同的内容(或者根本不呈现)。

    {this.props.unreadMessages.length > 0 &&
        <h2>
          You have {this.props.unreadMessages.length} unread messages.
        </h2>
    }
    

    if (this.props.unreadMessages.length > 0) {
      return <Main unreadMessages={this.props.unreadMessages} />;
    } else {
      return <Loading />
    }
    

    您还可以拥有默认的初始状态,并根据该状态进行渲染 props

    <h2>
     Hello, {this.props.username || this.state.username}.
    </h2>
    

    另外,推荐的Ajax调用的生命周期钩子是 componentDidMount .

        2
  •  0
  •   Anthony Liu    6 年前

    如果数据尚未就绪,可以使用条件呈现。添加有关数据的其他指标,如下所示

     render() { 
        if (!this.props.data) { 
           return null;
        }
        return <YourComponent />;
    }
    

    你最好把数据拿进来 componentDidMount 生命周期。

        3
  •  0
  •   P Ackerman Lucas Alves Costa    6 年前

    我将在render方法中使用三元表达式作为一种保护子句来检查props。像这样的事情,例如:

    render(){
        return (<React.Fragment>
        { this.props.user ? <IntendedComponent ...this.props.user /> : <Loading user={defaultUser}/> }
        <React.Fragment/>);
    }
    

    如果尚未填充用户属性,则该属性应为空,并显示备用组件(如示例中的加载组件)或具有默认硬编码值的预期组件。数据就位后,可以根据需要将数据传递给零部件。

        4
  •  0
  •   Just code    6 年前

    首先,componentWillMount不是调用api的好方法, 根据react文件:

    装入(插入树中)。需要DOM的初始化 这是实例化网络请求的好地方。

    此方法是设置任何订阅的好地方。如果你这样做了

    以下是链接: https://reactjs.org/docs/react-component.html#componentdidmount

    把一个旗子放进redux州 dataLoaded:false 一旦数据被加载,你就可以很容易地修改它。

    render()

    if(this.props.dataLoaded){
      <loadingComponent></loadingComponent>
    } else {
      //operation is performed
    }
    
        5
  •  0
  •   Cuong Vu    6 年前

    Redux ,可以设置默认值 Redux state 在里面 Reducers 使用ES6默认参数。像这样:

    const apiStatus = (state='fetching', action) => {
       // handle dispatch action
    }
    

    在React中,你可以使用 Conditional Rendering render 例如,当状态为 fetching finished ,获取结果并 提供 真正的元素。

    Async Action