簡體   English   中英

如何在孩子的 componentDidMount 反應中從父級設置變量?

[英]How to set variable from parent inside child's componentDidMount react?

我正在嘗試從子組件中的 Api 請求中獲取信息。 問題是我遇到了訪問父母的道具。 更准確地說,如何獲取父級的道具並將其設置在 componentDidMount() 中? 父組件

class Parent extends Component {
  constructor(){
    super()
  }
...
<Child id={id}/>
...

export default Parent;

子組件

class Child extends Component {
  constructor(){
    super()
    this.state = { 
      id:'',
    }
  }

  // I need somehow set parent's "id" inside the url
  componentDidMount() {
    const url = `https://api.../${id}?api_key=${apiKey}`;

        axios.get( url )
        ...
    };

  render(){

    const { id } = this.props;
    console.log('Child id ' + id) // here I see all ids

    return(
      <div className="item" key={id}>
        <p>{id}</p> // here as well
      </div> 
    )
  }
}

Child.propTypes = {
  item: PropTypes.object
}
export default Child;

也許我在錯誤的地方尋找,我只需要改變邏輯。 我將不勝感激任何建議

要從 Child 組件中的任何位置訪問 props,您需要將 props 傳遞給構造函數,然后您只需使用 this.props 訪問它。

這應該有效:

class Child extends Component {
  constructor(props){
    super(props)
    this.state = {},
  }

  componentDidMount() {
    const id = this.props.id
    const url = "https://api.../$" + id + "?api_key=${apiKey}";

        axios.get( url )
        ...
    };
}

如果組件中有構造函數,則應始終將 props 傳遞給構造函數,並使用 super() 傳遞給 React 組件

constructor(props){
    super(props)
}

在您的情況下,如果您必須使用您的父母道具,您還應該將父母道具也傳遞給孩子,並且在構造函數中使用相同的語法,您可以使用您在子組件的任何地方傳遞的道具,並且您也可以在 componentDidMount 中設置該道具

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM