【发布时间】:2020-08-05 06:58:55
【问题描述】:
所以我在我的 node/express 后端执行 SQL 查询,并通过 JSON 将结果发送到我的 React 前端。我是 console.log 来查看我发送的信息,这似乎是有序的。但是,我似乎无法弄清楚如何将这个对象数组设置为我的状态。我收到此错误:
“对象作为 React 子对象无效(找到:带有键 {Title} 的对象)。如果您要呈现子对象的集合,请改用数组。”
这是我正在使用的组件:
import React, { Component } from 'react'
export class ShoppingCart extends Component {
state = {
cartItems: ['Title 1']
};
displayCart = () => {
console.log('call it')
console.log('hello from displaycart');
fetch('http://localhost:5000/fillCart')
.then((res) => res.json())
.then((json) => {
this.setState(state => {
const cartItems = state.cartItems.concat(json.Title);
return {
cartItems
};
});
})
}
componentDidMount() {
this.displayCart();
}
render() {
return (
<div className="ShoppingCart">
<h3>This is your shopping cart</h3>
<ul>
{this.state.cartItems.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
)
}
}
export default ShoppingCart
我的目标是将 json.Title(现在包含多个标题)设置到我所在州的 cartItems State 数组中,然后通过 render() 在列表中显示每个标题。但是,我对如何做到这一点感到困惑。
另外,这是我从 Node/express 后端发送的 json 数据的样子:
[
RowDataPacket { Title: 'The Tragedy of The Korosko' },
RowDataPacket { Title: 'Two in the Far North' }
]
为了澄清,此时我的问题不是显示信息,而是首先将其设置为状态。 任何建议肯定会受到赞赏!我已经坚持了好几天了。提前谢谢!!!
【问题讨论】:
-
您能展示一下 JSON 响应的结构吗?
-
显示 json 数据。
-
这是我发送给 React 的 json 格式:[ RowDataPacket { Title: 'The Tragedy of The Korosko' }, RowDataPacket { Title: 'Two in the Far North' } ]
-
请将其添加到原始问题中,而不是在评论中。真的很难读。
-
我刚刚将json数据添加到原始问题中。
标签: javascript arrays reactjs state javascript-objects