【问题标题】:Want to pass data from componentDidMount but it's always undefined想要从 componentDidMount 传递数据,但它总是未定义
【发布时间】:2020-06-11 09:11:15
【问题描述】:

在componentdidmount中从服务器获取数据并传递给handlesubmit函数,但它总是返回未定义:

    constructor() {
    super();
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch(BASE_URL_API + "/payments/subscriptions/")
      .then(res => res.json())
      .then(json => this.setState({ data: json }));
  }

  handleSubmit = async event => {

    event.preventDefault();

    const data = this.props;

    console.log("Token is: ", data);

  };

【问题讨论】:

  • 这里的问题不止一个:您必须调用res.json().then.... 而不是res.json()).then...,您尝试设置state 但您正在阅读props (const data = this.props)
  • 等等,你有来自 props 的数据,还是有错误?

标签: javascript django reactjs django-rest-framework


【解决方案1】:

如果我正确理解您的问题,它应该是const data = { this.state };,因为您将数据存储在状态中。

props 对象用于传递到您的组件中的数据,如here 所述。

【讨论】:

  • componentDidMount 中的承诺链也不正确...
【解决方案2】:

应该是const { data } = this.props; 而不是const data = this.props;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2018-04-23
    相关资源
    最近更新 更多