首页 > 解决方案 > 如何在孩子的 componentDidMount 反应中从父级设置变量?

问题描述

我正在尝试从子组件中的 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;

也许我在错误的地方寻找,我只需要改变逻辑。我将不胜感激任何建议

标签: javascriptreactjsapi

解决方案


要从 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 )
        ...
    };
}

推荐阅读