为什么我在跟踪React JS时会出现空白屏幕?

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

我正在关注当前的教程:Youtube tutorial at 12:51 mins.

我希望在屏幕上看到一堆帖子,但我的屏幕仍然是空白的。看来我已经按照教程中的所有内容进行了操作。

import React, { Component } from 'react';

class Posts extends Component {

    constructor(props) {
        super(props);
        this.state = {
            posts: []
        }
    }

    componentWillMount() {
        fetch('https://jsonplaceholder.typicode.posts')
            .then(res => res.json())
            .then(data => this.setState({posts: data}))
    }

    render() { 
        const postItems = this.state.posts.map(post => (
            <div key={post.id}>
                <h3>{post.title}</h3>
                <p>{post.body}</p>
            </div>
        ));
        return ( 
            <div>
                <h1>Posts</h1>
                { postItems }
            </div>
         );
    }
}

export default Posts;

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

class App extends Component {

  render() {
    return (
      <div className="App">
        <Posts />
      </div>
    );
  }
}

export default App;

我的浏览器屏幕仍为空白,我在控制台上看不到任何错误。我错过了什么?

reactjs
2个回答
2
投票

不知道该教程,但它看起来过时了...

这是你的App.js(父组件):

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

export default class App extends Component {
  state = { posts: [] };

  //fetch the posts and store them in the state
  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(posts => this.setState({ posts }))
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div>
        {/* pass the state (posts) as props to Posts */}
        <Posts posts={this.state.posts} />
      </div>
    );
  }
}

这是你的Posts.js:

import React from 'react';

// No need for a class based comp
// destructure the props and you have all your data 
const Posts = ({ posts }) => (
  <div>
    {posts.map(post => (
      <div key={post.id}>
        <h3>{post.title}</h3>
        <p>{post.body}</p>
        <hr />
      </div>
    ))}
  </div>
);

export default Posts;

现场演示:https://jsfiddle.net/ctszdue9/7/


0
投票

尝试将副作用/ api调用放入其中

componentDidMount() { }

更改网址

https://jsonplaceholder.typicode.posts/

https://jsonplaceholder.typicode.com/posts
© www.soinside.com 2019 - 2024. All rights reserved.