更新状态未在子组件中呈现

时间:2019-04-09 01:14:41

标签: reactjs

我正在尝试从NASA的API中提取图片,以获取当天的天文学图片。当我在API调用和console.log this.state.picture中更新状态时,可以看到该图片已设置为数据对象。但是,当我尝试在render中记录图片时,它记录了一个空数组。我在以前的作业中使用了类似的方法,但从未遇到过此问题,因此我真的无法弄清楚自己在做什么错。我是React的新手,如果答案真的很明显,那么对不起。

父组件:

class App extends Component {
  state = {
    picture: [],
    asteroids: [],
  }

  render() {
    return (
      <div className="App">
        <Route exact path="/" component={Homepage}/>

        <Route path="/apod" render={() => 
          <APOD picture={this.state.picture}/>}/>

        <Route path="/asteroids" render={() =>
          <Asteroids asteroids={this.state.asteroids} />} />
      </div>
    );
  }
}

export default App;

子组件:

class Apod extends React.Component{
  getApodPicture = e => {
    e.preventDefault();

    let url = `https://api.nasa.gov/planetary/apod?api_key=v1sEi9chxFYzrf1uXei0J1GvXaemhnQXiDjEcnK2`;
    fetch(url)
      .then(res => {
        if (!res.ok){
          throw new Error (res.status)
        }
        return res.json();
      })
      .then(data => {
        this.setState({picture: data})
        console.log(this.state.picture) // logs the data object from NASA
      })
      .catch(err => console.log(err))
  }

  render(){
    console.log(this.props.picture) // logs []
    // console.log(this.state.picture) // returns "Cannot read property 'picture' of null"
  return(
    <div>
      <h1>Astronomy picture of the day!</h1>
      <Link to="/">Back to homepage</Link>

      <section>
        <button onClick={e => this.getApodPicture(e)}>Click to see picture</button>
      </section>
    </div>
  )
  } 
}

export default Apod;

1 个答案:

答案 0 :(得分:1)

This.setState将设置组件的状态,而不是父组件的状态。

您将需要一个changeHandler以获得所需的结果。

类似


class App extends Component {
  state = {
    picture: '',
    asteroids: [],
  }

  pictureChangeHandler = value => {
    this.setState(value);
  }

  render() {
    return (
      <div className="App">
        <Route exact path="/" component={Homepage}/>

        <Route path="/apod" render={() => 
          <APOD pictureChangeHandler={this.pictureChangeHandler} 
 picture={this.state.picture}/>}/>

        <Route path="/asteroids" render={() =>
          <Asteroids asteroids={this.state.asteroids} />} />
      </div>
    );
  }
}

export default App;

class Apod extends React.Component{
  getApodPicture = e => {
    e.preventDefault();

    let url = `https://api.nasa.gov/planetary/apod?api_key=v1sEi9chxFYzrf1uXei0J1GvXaemhnQXiDjEcnK2`;
    fetch(url)
      .then(res => {
        if (!res.ok){
          throw new Error (res.status)
        }
        return res.json();
      })
      .then(data => {
        this.props.pictureChangeHandler(data)

      })
      .catch(err => console.log(err))
  }

  render(){
    console.log(this.props.picture) // logs []
    // console.log(this.state.picture) // returns "Cannot read property 'picture' of null"
  return(
    <div>
      <h1>Astronomy picture of the day!</h1>
      <Link to="/">Back to homepage</Link>

      <section>
        <button onClick={e => this.getApodPicture(e)}>Click to see picture</button>
      </section>
    </div>
  )
  } 
}