简体   繁体   中英

React - updated state observed with useSelector() doesn't render new components

I'm using Redux Toolkit and Redux Thunk. I successfully get my data asynchronously from a data source back into my component. Inside my component, I can observe the data coming with useSelector: const booksData = useSelector((state) => state.books);

At this point, I would like to loop the books I'm getting and render my Book component for each book data I'm getting:

  const renderBooks = (books) => {
    books.map((book) => {
      console.log(book.id);
      <Book props={book}/>;
    });
  };

Problem is, I can see this renderBooks is called and bookId s logged for each book. The <Book> component is not rendered though.

Am I missing something obvious? Isn't the useSelector a state like useState so it should trigger rendering once updated?

Thanks in advance.

Rendering code (simplified to cut noise):

  return (
    <React.Fragment>

{/*some usual HTML here */}

      <div>{renderBooks(booksData.books)}</div>
    </React.Fragment>
  );

You need to return the values:

  const renderBooks = (books) => {
  return  books.map((book, index) => {
      console.log(book.id);
     return <Book key={index} props={book}/>;
    });
  };

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