如何使用fetch来发布一些数据

问题描述 投票:0回答:1

我只是想知道是否可以使用从 MoviesDB 获取 API 来发布数据。我能够将信息发布到控制台。但现在我想在我的 React 页面上实际渲染。下面是我的代码。如有任何帮助,我们将不胜感激。

import React, {Component} from 'react';
import './App.css';            

class Home extends Component{

  constructor(props) {
    super(props);

    this.state = {
      posts:{}
    }
    
  }

  getPost = () => {
    return fetch("https://api.themoviedb.org/3/movie/550?api_key=54a83919a7f93d82a8b8bdd417544d6f")
  .then(res=>res.json())
  .then(posts => console.log(posts))
  }
      
render() {
  
    return (
      <div className="App">
      <div className="headings">
      <img className="LOGO" src="https://www.moonlight.com.au/wp-content/themes/moonlight-2016/dist/images/moonlight-logo.png" alt="back"/>
      <input className="input"
        placeholder="Enter a movie title" />
        <button onClick={this.getPost}>Get post</button>
        <div>{JSON.stringify(this.state.posts)}</div>
        </div>
      </div>
    );
    }
}
    
export default Home;
javascript reactjs post get fetch-api
1个回答
0
投票

在您的渲染方法中,您正在使用

this.state.posts
但您没有在任何地方更新它。

.then(posts => console.log(posts))
替换为
.then(posts => this.setState({ posts }))

© www.soinside.com 2019 - 2024. All rights reserved.