react组件父传子异步传参

1,943 阅读1分钟

需求

父组件异步请求拿到数据,子组件接收此数据

解决

我们先看看在vue中是怎样实现的,参考以前文章
vue中, 父组件请求拿到数据, 利用props传给子组件, 子组件通过watch监听props拿到值
react中也是这样的思路。

代码

  • 父组件fahter.js

我们在父组件内利用Promise模拟接口请求,传递fatherList给子组件

import React from 'react'
import Child from './child' //引入子组件

export default class Father extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      fatherList: [],
    }
  }
  render() {
    return (
      <div className={'father panel'}>
        <h2>我是father父组件</h2>
        {/*子组件child*/}
        <Child
          fatherList={this.state.fatherList}
        />
      </div>
    )
  }
  async componentDidMount() {
    const res = await this.getAsyncData()
    this.setState({fatherList: res})
  }
  getAsyncData() {
    return new Promise(resolve => {
      resolve ([1,2,3])
    })
  }
}
  • 子组件

我们通过componentDidUpdate来监听state内的值, 具体用法看下面注释。componentDidUpdate文档

import React from 'react'

export default class Child extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      childList: [],
    }
  }
  render() { //这里也可以直接拿到this.props.fahterList
    return (
      <div className={'child panel'}>
        <h2>我是child子组件</h2>
      </div>
    )
  }

  /**
   *
   * @param prevProps
   * @param prevState
   * @param snapshot
   * componentDidUpdate
   更新完成函数。

   📜 语法:componentDidUpdate(nextProps, nextState, snapshot)

   ⏱ 触发时机:组件每次重新渲染后触发,相当于首次渲染(初始化)之后触发 componentDidMount ,

   🎉 适用场景:操作 DOM;发送网络请求。
   */
  componentDidUpdate(prevProps, prevState, snapshot) {
    //判断这次和上次的内容不一样时赋值,不然会进入死循环
    if(JSON.stringify(this.props.fatherList) !== JSON.stringify(prevProps.fatherList)){
      this.setState({childList: this.props.fatherList})
    }
  }
}