簡體   English   中英

道具在控制台中工作,但不在前端渲染-React

[英]props working in console, but not rendering on front end - React

我正在開發一個React應用程序,卻遇到了這個奇怪的錯誤,我試圖在前端顯示props的值,但是卻什么也沒顯示,但是如果我嘗試console.log這些console.log的值,我獲得正確的值。 這是我的代碼。

import React, { Component } from 'react';
import { connect } from 'react-redux';

class BookList extends Component{

    renderBooks = () => {
        if( this.props.books.length === 0 ){
            console.log("No books");
            return <p>Getting books...</p>
        }else{
            console.log( this.props.books[0].id );
            return <h2> { this.props.books[0].id }</h2>//this.props.books.map(( book ) => {
            //     return (
            //         <div key={ book.id }>
            //             <h2>{ book.title }</h2>
            //             <h2>{ book.description }</h2>
            //             <h3>{ book.price }</h3>
            //         </div>
            //     )
            //});
        }
    }
    render(){
        return(
            <div>
                { this.renderBooks() }
            </div>
        )
    }
}

function mapStateToProps( state ){
    return {
        books: state.books.books
    }
}

export default connect( mapStateToProps )(BookList);

地圖功能也不起作用。 在控制台中,我獲得了正確的props值,當我嘗試檢查此<div>的HTML元素時,我得到了這個。

<div>
    <h2></h2>
</div>

標簽中沒有任何內容。 為什么會發生這種情況,我該如何解決?

用這種方式調試呢?

let dummyBooks = [
  { id: 1, title: 't1', description: 'd1', price: 1 },
  { id: 2, title: 't2', description: 'd2', price: 2 },
];

return dummyBooks.map(( book ) => {
   return (
       <div key={ book.id }>
          <h2>{ book.title }</h2>
          <h2>{ book.description }</h2>
          <h3>{ book.price }</h3>
       </div>
   )
});

如果還可以-那么錯誤肯定是關於

this.props.books

也許它是一個對象,而不是數組?

不確定父組件的外觀如何,但這是組件的快速示例https://codesandbox.io/s/w263l83y1k

問題出在你的減速機上

將您的bookReducer替換為以下代碼即可工作

export function booksReducers( state = { books:[] }, action ){
switch( action.type ){

    case "POST_BOOK":
        return Object.assign({}, state, {
            books: action.payload
        })
        break;

    case "DELETE_BOOK":
        return Object.assign({}, state, {
            books: state.books.filter(book => {
                if (book.id !== action.payload.id) {
                    return true
                }
            })
        })
        break;

    case "UPDATE_BOOK": 
    return Object.assign({}, state, {
        books: state.books.map(book => {
            if (book.id !== action.payload.id) {
                return book
            } else {
                return action.payload
            }
        })
    })
        break;
}

return state;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM