使用带有响应的axios从服务器获取数据

时间:2019-12-05 19:06:50

标签: reactjs axios

我是使用React的新手,我想从服务器获取数据,所以我尝试:

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = { movies: [] }
  }

  componentDidMount() {
    axios.get('https://facebook.github.io/react-native/movies.json')
      .then(response => this.setState({ movies: response.data.data }))
  }

  renderUsers() {
    const { movies } = this.state

    return movies.map( user => (
      <div key={id}>{title} {releaseYear}</div>
    ))
  }

  render() {
    return <div>{ this.renderUsers() }</div>
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
)

和我的html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>

  <div id="container"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="movies.js" type = "text/babel"></script>

  </body>
</html>

问题是,我的页面没有任何内容。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我已解决的几个问题

    componentDidMount中的
  • setState选择错误的密钥。您需要设置response.data.movi​​es而不是response.data.data
  • map函数在renderUsers函数中使用不正确。您需要从正确的变量中选择id,title和releaseYear,而不是直接使用它们

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = { movies: [] }
  }

  componentDidMount() {
    axios.get('https://facebook.github.io/react-native/movies.json')
      .then(response => this.setState({ movies: response.data.movies }))
  }

  renderUsers() {
    const { movies } = this.state

    return movies.map( data => (
      <div key={data.id}>{data.title} {data.releaseYear}</div>
    ))
  }

  render() {
    return <div>{ this.renderUsers() }</div>
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>

  <div id="container"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="movies.js" type = "text/babel"></script>

  </body>
</html>