我正在尝试从本地json文件中获取数据。 提取数据不会出错,并且控制台日志中的所有内容均正确返回。 当我尝试将数据设置为状态时,如果我解析json而不解析json.data,则它可以工作。 json.data什么也不做,但是json可以工作,只有当我使用map函数时,它才会给我带来很多错误
代码:
getData = () => {
fetch('http://localhost:3000/ingredients.json')
.then(response => {
if (response.ok) {
return response;
} else {
let response = `${response.statusText}`
let errorMessage = `${response.status(response)}`
let error = new Error(errorMessage)
throw (error)
}
})
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ data: json })
console.log(this.state)
});
}
render() {
return (
<div>
{
this.state.data &&
this.state.data.map((key, display, nutrition) =>
<div key={key}>
{display}
{nutrition}
</div>
)}
</div>
)
}
这是我的错误:
Objects are not valid as a React child (found: object with keys {key, display, unity, category, nutrition, vitamins}). If you meant to render a collection of children, use an array instead.
答案 0 :(得分:0)
map
的{{1}}函数接受带有参数Array.prototype
的函数回调。如果您打算破坏结构,请改用
(value, index) => {}
修改:
我假设this.state.data.map({key, display, nutrition, ...rest}, index) => { // index of value in this.sta
<div key={key}>
{display} //I am assuming this is a string not a object or array
{nutrition} // this should be a string
</div>
}
就像
data
编辑2 :
给出这个
data: [
{
key: "",
nutrition: "",
display: ""
},
{
key: "",
nutrition: "",
display: ""
}
]
这里是显示方式:
state {
data =
[
{ id: 1,
display: 'Pommes',
unity: [ 'unités' ],
category: [ 'fruits' ],
nutrition: 95,
vitamins: [ 'C', 'B-6' ]
},
{
id: 2,
display: 'Poires',
unity: [ 'unités' ],
category: [ 'fruits' ],
nutrition: 95,
vitamins: [ 'C', 'B', 'E' ]
}
];
}
答案 1 :(得分:0)
如果您的数据不是数组,请不要使用地图功能。如下更改代码:
render() {
return (
<>
{
this.state.data && this.state.data.map(({id, display, nutrition, vitamins}) => {
return (
<div key={id}>
{display}
{nutrition}
{<>vitamins.map(v => v) </>} //in case you need thing such as vitamis, Array, also to eppear
</div>
)})
}
</>
)
}