javascript - “TypeError:无法将未定义或 null 转换为对象”呈现嵌套 JSON
问题描述
我正在尝试在反应中渲染嵌套的 JSON,但是当我尝试渲染嵌套部分时收到错误“TypeError:无法将未定义或 null 转换为对象”。当通过 componentDidMount() 方法存储在组件的状态中时,这些部分将转换为对象,因此我正在尝试使用 Object.keys() 函数。例如,在下一个 JSON 中:
{
"gear": 14,
"valid": 1,
"meteo": {
"wind_direction": 152,
"wind_velocity": 10.1
},
}
当我尝试使用 Object.keys() 函数渲染它时,如下所示:
const haul = this.state.haul
{Object.keys(haul.meteo).map( key => {
return(<p>Sea state: {haul.meteo[key]} </p>)
})}
错误是在 Object.keys() 行中引发的,我不明白为什么。
完整的组件是这样的:
class ComponentsHaul extends Component {
constructor(props) {
super(props);
this.state = {
haul: []
};
this.apiHaul = "http://myapi";
}
componentDidMount() {
fetch(this.apiHaul)
.then(response => {
return response.json();
})
.then(haul => {
this.setState(() => {
return {
haul
};
});
});
}
render() {
const haul = this.state.haul
return (
<Fragment>
<p>Gear: {haul.gear}</p>
{Object.keys(haul.meteo).map( key => {
return(<p>Sea state: {haul.meteo[key]} </p>)
})}
</Fragment>
);
}
}
解决方案
haul
最初是一个数组,没有meteo
,所以Object.keys(haul.meteo)
失败。然后,您稍后将类型(a no-no)更改为对象,保持类型一致。
const state = { haul: [] };
console.log(Object.keys(state.haul.meteo));
如果您更改初始状态以提供一个空meteo
对象,这应该适用于您在获取数据时的初始和后续渲染。
this.state = {
haul: {
meteo: {},
},
}
const state = { haul: { meteo: {} } };
console.log(Object.keys(state.haul.meteo));