如何在React中按索引访问状态值

时间:2019-03-06 12:13:38

标签: reactjs axios jsx

我正在努力使用axios在React的状态内访问值,我的代码如下:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class App extends React.Component {
  state = {
    moviedata:null
  }

  getMovies(){
    axios.get("http://127.0.0.1:8000/api/v1/movies/")
      .then(moviedata => {
        this.setState({
          moviedata: moviedata.data    
        });
      })
      .then(x => { console.log(this.state.moviedata)});
  }

  componentDidMount(){
    this.getMovies();
  }

  render () {
    return <h1>Movie Examples include </h1>
  }
}

ReactDOM.render(<App />, document.getElementById('react-app'));

console.log如下所示:

0: {title: "Terminator 2: Judgement Day", plot: "Rise of the machines.", year: 1991}
1: {title: "The Italian Job", plot: "A comic hinging on a traffic jam", year: 1969}

如何在h1标签中的“包含”一词之后添加第一个条目的标题,即“终结者2:审判日”?

我尝试过:

render () {
  return <h1>Movie Examples include {this.state.moviedata[0].title}</h1>
}

出现错误TypeError: Cannot read property '0' of null

3 个答案:

答案 0 :(得分:1)

moviedata在您的组件状态最初是null,因此尝试从中访问[0]会引起错误。

您可以例如从render方法提早返回,直到设置了moviedata

示例

class App extends React.Component {
  // ...

  render() {
    const { moviedata } = this.state;

    if (moviedata === null) {
      return null;
    }
    return <h1>Movie Examples include {moviedata[0].title}</h1>;
  }
}

答案 1 :(得分:0)

首先,您必须“知道”组件处于“正在加载”状态。否则,您的状态数据将无法定义(仍然加载)

方法如下:

class App extends React.Component {
  state = {
    moviedata:null,
    isLoading: true
  }

  getMovies(){
    axios.get("http://127.0.0.1:8000/api/v1/movies/")
      .then(moviedata => {
        this.setState({
          moviedata: moviedata.data,
          isLoading: false
        });
      })
      .then(x => { console.log(this.state.moviedata)});
  }

  componentDidMount(){
    this.getMovies();
  }

  render () {
    if (this.state.isLoading) {
      return <h1>Please wait...</h1>
    }

    // show only the first movie
    return <h1>Movie #1 {this.state.moviedata[0].title}</h1>;

    // show all the movies
    return (
      <>
        {this.state.moviedata.map((m, idx) => <h1 key={idx}>Movie: {m.title}</h1>}
      </>);
  }
}

答案 2 :(得分:0)

您必须考虑到Axios请求是异步的这一事实,因此组件可能会在加载数据之前呈现。例如:

render () {
  const data = this.state.moviedata;
  return <h1>Movie Examples include {data ? data[0].title : ""}</h1>
}
相关问题