gpt4 book ai didi

javascript - 为什么 React JS 会发生这种情况?

转载 作者:行者123 更新时间:2023-11-30 23:55:34 24 4
gpt4 key购买 nike

我正在尝试使用 React JS 获取数据,但我的控制台中出现以下错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {productsList}). If you meant to render a collection of children, use an array instead.

这是我的代码:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Products extends Component {
constructor(props) {
super(props);
this.state = {
products: []
};
}

//Lifecycle hook
componentDidMount () {
axios.get('/api/storageapp')
.then(response => {
console.log(response)
this.setState({
products: response.data,
})
})
}
render() {
const { products } = this.state;
const productsList = products.length ? (
products.map(product => {
return (
<div key={product.id}>
<div>{product.product_name}</div>
</div>
)
})
) : (
<div>No products were found.</div>
)

return (
{productsList}
);
}
}
export default Products;

if (document.getElementById('products')) {
ReactDOM.render(<Products />, document.getElementById('products'));
}

知道发生了什么吗?

最佳答案

因为你要返回一个对象:

    return (
{productsList}
);

您应该返回productsList。摆脱它周围的对象文字语法。

return productsList;

关于javascript - 为什么 React JS 会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61081388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com