【问题标题】:How to fetch data asynchronously inside component and pass it as props to another component in render?如何在组件内部异步获取数据并将其作为道具传递给渲染中的另一个组件?
【发布时间】:2017-05-08 07:17:39
【问题描述】:

我有一个 react 应用程序,我想异步获取一些数据,对其进行处理,更改当前组件状态,然后将其作为 props 传递给渲染中的另一个组件。我尝试在 componentWillMount 中获取它,但似乎渲染仍然在获取数据之前发生。什么是可行的解决方案?我还尝试在 ES6 构造函数中获取数据,但问题仍然存在。

非常感谢任何帮助!

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    那么,获取数据的理想位置是 componentWillMount 函数,但是由于异步特性,您的子组件可能会在获取数据之前被渲染,因此您可以做两件事。

    保持一个加载状态,在获取结果之前不渲染组件,例如:

    constructor() {
       super();
       this.state = {
            isLoading: true,
            // other states
       }
    }
    
    componentWillMount() {
        //your async request here
    }
    
    render() {
       if(this.state.isLoading) {
           return null; // or you can render laoding spinner here
       } else {
           return (
               //JSX here with the props
           )
       } 
    }
    

    另一种方法是有一个空的道具并在子组件中执行检查:

    constructor() {
        super();
        this.state = {
            someProps: null; 
        }
    } 
    
    componentWillMount() {
         //your async request here
    }
    
    render() {
    
        return (
             <Child someProps={this.state.someProps}/>
        )    
    }
    

    儿童

    render() {
    
      if(this.props.someProps == null) 
            return null;
      else {
          return (//JSX contents here);
      }
    }
    

    【讨论】:

    • 我个人更喜欢第一种方法
    • 由于某种原因,我的单元测试现在失败了。在不崩溃的情况下渲染对象的基本测试失败。它与上述解决方案有何关系,我该如何解决?
    • 可能你还没有处理加载条件,我对单元测试不太了解,所以可能帮不了你。
    • 如果它有帮助,你能接受这个作为答案吗?如果你想不出来,请另一个人进行单元测试
    • 当然:) 谢谢!抱歉,我是使用 StackOverflow 的新手,仍在弄清楚它是如何工作的
    猜你喜欢
    • 2017-12-19
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多