如何在React中将ID传递给componentdidmount

时间:2019-08-29 10:26:40

标签: javascript reactjs ecmascript-6

我有功能,我想将ID传递给componentDidMount。我努力尝试,但是没有找到任何解决方案来实现我的目标。实际上我有renderEvent()函数,在这个函数中我有customerID,我想在componentdidmount中使用此ID进行API调用。有人可以帮我解决这个问题

代码

  componentDidMount() {
    .../ want to access CustomerID here 
  }


renderEvent() {
 <p>Customer Name : {slotInfo.customerId}
}

想将此客户ID发送到up componentdidmount函数

3 个答案:

答案 0 :(得分:1)

是的,但是进一步的代码将取决于您从何处获得slotInfo.

componentDidMount() {
    const custId = getCustomerId()
}

getCustomerId=()=> slotInfo.customerId

renderEvent() {
    return 
 <p>Customer Name : {getCustomerId()}
}

答案 1 :(得分:0)

您的组件应这样呈现:

class Component extends React.Component {
    componentDidMount() {
        console.log(this.props.slotInfo); // Here you can access your prop.
    }

    render() {
          const { slotInfo } = this.props;

          return <p>Customer Name: {slotInfo.customerName}</p>;
    }
}

class Layout extends React.Component {
    render() {
        return <Component slotInfo={{ customerName: 'Bob' }} />;
    }
}

通过这种方式,您可以随时随地访问道具。目前,我无法告诉您如何加载数据。但这就是您应该这样做的方式。

答案 2 :(得分:0)

如果if是由父组件提供的,则可以从属性中检索该ID:

componentDidMount() {
   this.custId = this.props.customerId;
}

renderEvent() {
    return 
 <p>Customer Name : {this.custId}
}

或更好的构造方法:

constructor(props) {
    super(props);
    this.custId =props.customerId;
}

renderEvent() {
    return <p>Customer Name : {this.custId}
}

上面的代码使用平面属性,但是您可以将slotInfo obj传递给您