简体   繁体   中英

React component console.logs 2 times in render()

for some reason, console.log outputs 2 times for each book. I've tried creating new project and still get the same result.

If I convert class based component and try to log props, I get 1 log for each element like I should. It happens in react version 16.13.1 and not in 16.8.3

Thanks!

Booklist component

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

class Booklist extends Component {
  state = {
    books: [
      {
        book: 'book nr 1',
        author: 'john doe',
      },
      {
        book: 'book nr 2',
        author: 'bob doe',
      },
      {
        book: 'book nr 3',
        author: 'peter doe',
      },
    ],
  };

  render() {
    console.log(this.state.books);
    return (
      <section>
        <h3>This is our Booklist</h3>
        <Book book={this.state.books[0]} />
        <Book book={this.state.books[1]} />
        <Book book={this.state.books[2]} />
      </section>
    );
  }
}

export default Booklist;

console

Book component

import React, { Component } from 'react';

class Book extends Component {
  render() {
    const { book, author } = this.props.book;
    return (
      <article>
        <h3>book:{book}</h3>
        <h4>author:{author}</h4>
      </article>
    );
  }
}

export default Book;

App.js

import React from 'react';
import Booklist from './Booklist';
import './App.css';

const App = () => {
  return (
    <section>
      <Booklist />
    </section>
  );
};

export default App;

Can you please provide code for the parent div and also the Book Component. Also you should not be setting the state in the render method, you should be using the constructor or component will mount lifecycle event to set the state.

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

class Booklist extends Component {
  componentWillMount(){
   this.state = {
        books: [
          {
            book: 'book nr 1',
            author: 'john doe',
          },
          {
            book: 'book nr 2',
            author: 'bob doe',
          },
          {
            book: 'book nr 3',
            author: 'peter doe',
          },
        ],
      };
  }

  render() {
    console.log(this.state.books);
    return (
      <section>
        <h3>This is our Booklist</h3>
        <Book book={this.state.books[0]} />
        <Book book={this.state.books[1]} />
        <Book book={this.state.books[2]} />
      </section>
    );
  }
}

export default Booklist;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM