**我正在尝试从一些课程/视频中学习反应,我几次都收到了这个错误,并找出并解决了,但现在我不知道了。有人可以帮我吗?而且,我尝试不使用“ this”,但是它不起作用。这是错误:**
Unhandled Rejection (TypeError): this.state.categories.map is not a function
CategoryList.render
C:/Users/Casper/Desktop/Programlar/React-Dersleri/intro/src/CategoryList.js:31
28 | <div>
29 | <h3>{this.props.info.title}</h3>
30 |
> 31 | <ListGroup>
| ^ 32 | {
33 | this.state.categories.map(category => (
34 | <ListGroupItem active={category.categoryName===this.props.currentCategory?true:false}
View compiled
▶ 18 stack frames were collapsed.
(anonymous function)
C:/Users/Casper/Desktop/Programlar/React-Dersleri/intro/src/CategoryList.js:21
18 | }
19 |
20 | getCategories = ()=>{
> 21 | fetch("http://localhost:3000/categories")
| ^ 22 | .then(response=>response.json())
23 | .then(data=>this.setState({categories:data}));;
24 | }
这是我的代码:
import React, { Component } from 'react'
import Navi from './Navi' //bulunduğum klasörden naviiyi import et
import CartSummary from './CartSummary'
import ProductList from './ProductList'
import {ListGroup,ListGroupItem} from 'reactstrap'
export default class CategoryList extends Component {
state = {
categories: []
};
componentDidMount(){
this.getCategories();
}
getCategories = ()=>{
fetch("http://localhost:3000/categories")
.then(response=>response.json())
.then(data=>this.setState({categories:data}));;
}
render() {
return (
<div>
<h3>{this.props.info.title}</h3>
<ListGroup>
{
this.state.categories.map(category => (
<ListGroupItem active={category.categoryName===this.props.currentCategory?true:false}
onClick={()=>this.props.changeCategory(category)}
key={category.id}>
{category.categoryName}
</ListGroupItem>
))
}
</ListGroup>
{ <h4>{this.props.currentCategory}</h4> }
</div>
)
}
}
因为我们可以看到,您正确初始化categories
用[]
,我们知道的初始状态是没有问题的。所以我们看一下状态更新。
您要更新的唯一位置categories
是在这里:
getCategories = ()=>{
fetch("http://localhost:3000/categories")
.then(response=>response.json())
.then(data=>this.setState({categories:data}));;
}
因此,这意味着data
第二个.then
回调不是数组(因为如果是数组,它将有一个map
方法)。
有两个可能的原因:
端点返回的任何JSON都不只是类别数组。您需要查看devtools的“网络”选项卡,或在该.then
回调中放置一个断点,以便了解其实际返回的内容—可能是一个具有提供类别数组的属性的对象。
您根本看不到端点响应,但是仍然看到可以解析为JSON的内容。之所以会发生这种情况,是因为除非您从中打开该页面,否则http://localhost:3000
您将执行跨域ajax调用,除非响应包含必要的跨域资源共享标头,否则该域将被Same Origin Policy阻止允许它。(您的服务器可能还需要处理HTTP调用。)OPTIONS
关于#2,您可能会遗漏一个事实,因为您的代码已成为fetch
API脚枪的牺牲品,因此未获得成功的响应:您需要在调用之前检查HTTP是否成功json
,因为fetch
仅拒绝其对网络错误的承诺,而非HTTP错误。在我贫乏的小博客上可以找到更多有关它的信息,但基本上,您需要将其更改为:
getCategories = ()=>{
fetch("http://localhost:3000/categories")
.then(response => { // ***
if (!response.ok) { // ***
throw new Error("HTTP error " + response.status); // ***
} // ***
return response.json(); // ***
}) // ***
.then(data => this.setState({categories:data}))
.catch(error => { // ***
// Handle/report error. // ***
}); // ***
}
检查response.ok
是检查HTTP是否成功。另请注意,我添加了拒绝处理程序。您始终需要处理拒绝,或将promise链返回到可以实现的目标。(在这种情况下,您需要处理它;componentDidMount
不会。)
但是,再说一遍,可能还不能解决问题。我想说这很可能是#1的原因,如果SOP错误碰巧是您可以解析为JSON的东西,那将有些奇怪。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句