控制台日志中的常量作为未定义返回

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

我有以下代码:

import React, { Component } from 'react'
import PropTypes from 'prop-types';
import axios from 'axios';



export class BookItem extends Component {
    state = {
        imgUrl: '', 
        author: '', 
        isLoaded: false
    }
    static propTypes = {
        book: PropTypes.object.isRequired
    }
    componentDidMount() {
        const { featured_media, author } = this.props.book;
        const getImageURL = axios.get(`http://localhost:8000/wp-json/wp/v2/media/${featured_media}`);
        const getAuthor = axios.get(`http://localhost:8000/wp-json/wp/v2/users/${author}`);

        Promise.all([getImageURL, getAuthor]).then(res => {
            console.log(res)
        });
    }
    render() {
        const { title, excerpt } = this.props.book;
        return (
            <div>
                <h2> {title.rendered} </h2>
                <p dangerouslySetInnerHTML={{__html: excerpt.rendered}}/>
            </div>
        )
    }
}

export default BookItem

[当我尝试加载页面时,我从控制台收到以下错误:

无法加载资源:服务器以404状态(未找到)进行了响应

我认为这是由于以下路线而回来的:

http://localhost:8000/wp-json/wp/v2/users/undefined

据我所见,它看起来像是const,但未定义,但我不确定为什么。

-编辑-

这是Book组件的代码:

import React,{Component} from'react'从'axios'导入axios从'./BookItem'

导入BookItem
export class Books extends Component {
    state = {
        books: [], 
        isLoaded: false
    }

    componentDidMount() {
        axios.get('http://localhost:8000/wp-json/wp/v2/books')
            .then(res => this.setState({
                books: res.data,
                isLoaded: true
            }))
            .catch(err => console.log(err))
    }
    render() {
        const {books, isLoaded} = this.state
        if(isLoaded){
            return (
                <div>
                    {books.map(book => (
                        <BookItem key={book.id }book={book}/>
                    ))}
                </div>
            );
        }
        return (
            <div>
                <h3>Loading....</h3>
            </div>
        )
    }
}

export default Books
javascript reactjs wordpress wordpress-rest-api
1个回答
0
投票

此代码不足以解决您的问题,因为常量features_media和author来自道具。

您可以在调用BookItem的地方共享父组件的代码,也可以再次检查是否正确传递了道具。

例如

<BookItem featured_media="some_value" author="some_value">
© www.soinside.com 2019 - 2024. All rights reserved.