我得到了上面提到的错误。我已经完成了相关的线程链接,但没有解决我的问题。我知道当我尝试使用对象设置状态时会出现此问题而不是使用数组。
我有一个siteProductTestContainer.js
import React from "react";
import api from "../networking/api";
import ProductList from "./components/ProductList";
class siteProductTestContainer extends React.Component {
state = {
products: []
};
componentDidMount = () => {
//make an api call to get the data
const dataToSend = {
customerNumber: this.props.propsAppData["customerNumber"],
elid: this.props.propsAppData["elid"]
};
const callback = responseData => {
console.log("DataType of products-->", typeof this.state.products); //object
console.log("DataType of responseData", typeof responseData); //object
console.log("DataType of responseData.services-->", typeof responseData.services);
//object
this.setState({
products: responseData.services
});
console.log("After updating state");
console.log("Current state is ", this.state);
api.siteProduct(dataToSend, callback);
};
render() {
return ( <
div >
<
ProductList productList = {
this.state.products
}
name = "pourush" / >
<
/div>
);
}
}
export default siteProductTestContainer;
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/react.min.js"></script>
&#13;
所以,假设我将responseData中的数据作为:
{
"site-services": {
"cNum": "the customer number to whom the service belong to",
"eId": "the site elid whose services are requested",
"services": [
{
"name": "service 1",
"serviceId": "123456"
},
{
"name": "service 2",
"serviceId": "147852"
}
]
}
}
问题:在responseData中,我已经将服务作为一个对象数组,但我仍然无法使用setstate()进行映射?
答案 0 :(得分:0)
services
无法在responseData
下直接提供,您需要从"site-services"
获取
this.setState({
products: responseData["site-services"].services
});
答案 1 :(得分:0)
通常,这些类型的错误发生在组件嵌套的情况下,并且您试图将数据从父组件传递给子组件。
错误被冒泡并显示在顶部组件,但实际上错误发生在内部子项。
在Inner子组件的某处,我们需要循环使用Array对象来提取数据并正确呈现它。
我从父母调到孩子,这对我有用。