简体   繁体   English

如何根据父组件的 API 调用设置子组件的初始 state?

[英]How to set initial state of child component based on parent component's API call?

I have a parent component from which I am making an api call on componentDidMount.我有一个父组件,我正在从中对 componentDidMount 进行 api 调用。

I want to set the child component's initial state based on the response of the api.我想根据 api 的响应来设置子组件的初始 state。

How can I do this?我怎样才能做到这一点? The problem which I am facing is that the initial value of child component is set on the first render of the parent component.我面临的问题是子组件的初始值是在父组件的第一次渲染上设置的。

You can render the child component conditionally so it is not rendered until the call resolve, for example:您可以有条件地渲染子组件,以便在调用解决之前不会渲染它,例如:

class Parent extends Component {
  componentDidMount() {
    APICall.then(response => this.setState({ childState: response.data }));
  }
  render() {
    return (
      <div>
        {this.state.childState && <Child intialState={this.state.childState} />}
      </div>
    );
  }
}

You can fetch data in your parent component then pass it to the child.您可以在父组件中获取数据,然后将其传递给子组件。

import React, { useState, useEffect } from 'react';
import Child                          from './child';
import axios                          from 'axios';

const Parent = () => {

    const [data, setData] = useState();

    useEffect( () => {
        const endpoint = 'https//:fakedata.com'
        axios.get(endpoint).then((res) => setData(res));

    }, [])

    return (  
        data && <Child data={data}/>
    );
}

export default Parent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM