反应:使用async / await在表单提交后获取数据

时间:2018-12-19 23:08:45

标签: javascript reactjs async-await

我正在从API提取数据,但无法将其显示在屏幕上。当用户在表单中键入内容并单击提交按钮时,我想获取数据。 我有一个错误:

  

TypeError:无法读取null的属性“ main”

我不明白为什么这些数据没有显示在屏幕上。如果什么都不显示,对我来说将更有意义。但是,如果我注释此行,则ChildComponent的props.data.city正确显示。我的代码:

class ExampleComponent extends Component {
  state = {
    city: null
  }

  getData = async e => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    const getData = await fetch(`${url}${city}&appid=${key}`);
    const data = await getData.json();

    this.setState({
      city: data
    });
    console.log(this.state.city); // return correct value, not null
    console.log(this.state.city.main.temp_min); // return correct value, not null
  }
  render() {
    return (
      <>
        <FormComponent onSubmit={this.getData} />
        <ChildComponent data={this.state.city} />
      </>
    );
  }
}

const FormComponent = props => (
  <form onSubmit={props.getData}>
    <input type="text" name="city" />
    <button type="submit">do it</button>
  </form>
);

const ChildComponent = props => (
  <div>
    <h3>{props.data.city}</h3>
    <h4>{props.data.main.temp_min}</h4>
  </div>
);

1 个答案:

答案 0 :(得分:4)

由于已获取数据,因此无法立即使用(渲染时)。检查是否在子组件中定义了数据。有很多方法可以做到,但这应该足够

public function store()
{
    return $this->hasOne(Store::class);
}
相关问题