我有以下代码:
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'
导入BookItemexport 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
此代码不足以解决您的问题,因为常量features_media和author来自道具。
您可以在调用BookItem的地方共享父组件的代码,也可以再次检查是否正确传递了道具。
例如
<BookItem featured_media="some_value" author="some_value">