javascript - 如何从反应组件访问数组中的数组?
问题描述
我有这个数组:
{
"firstname": "Jessica",
"lastname": "Wood",
"favorite": {
"movie": Flint Town,
"drink": Sprite
}
}
我正在尝试喝酒,但发现对象无效,因为发现 React 孩子:带钥匙的对象。
我该如何解决?
我的反应组件:
import React, { Component } from 'react';
import axios from 'axios';
class Home extends Component {
state = {
info: []
}
componentDidMount() {
axios.get('http://localhost:9000/api')
.then(res => {
const info = res.data;
this.setState({ info });
})
}
render() {
return (
<ul>
<li>{this.state.info.favorite.drink}</li>
</ul>
)
}
}
export default Home;
解决方案
您需要解析“最喜欢的”对象中的值,以便它们可以呈现为字符串。
看起来您还试图在道具this.state.info
存在之前访问它。这就是为什么它给你未定义的错误。render 方法在您将任何内容分配给 info 之前运行,您在 componentDidMount() 中执行了此操作。
要解决此问题,我们可以使用 loading-state 值来确定要显示的内容。加载状态将在您的 componentDidMount() 逻辑完成后切换,确保您的状态已填充。
这是沙箱:https ://codesandbox.io/s/bold-germain-k3f23
class Home extends Component {
state = {
info: {},
loading: true
};
componentDidMount() {
axios.get("http://localhost:9000//").then(res => {
const info = res.data;
const parsedInfo = {
...info,
favorite: Object.entries(info.favorite).reduce((obj, [k, v]) => {
obj[k] = "" + v;
return obj;
}, {})
};
this.setState({ info: parsedInfo, loading: false });
});
}
render() {
const { loading, info } = this.state;
if (loading) {
return <div>Loading</div>;
} else {
return (
<div>
<div>{info.favorite.movie}</div>
<div>{info.favorite.drink}</div>
</div>
);
}
}
}
推荐阅读
- data-cleaning - OpenRefine - 将多个列值合并到新列中应该(?)工作
- jquery - 如何将 Angular 组件附加到 JqGrid 的单元格?
- nestjs - 在保存到嵌套数据库之前执行角色层次结构验证
- css - 使用 animate.css 库进行 nuxt 页面转换
- angular - 在 Ion-List 上显示数据
- reactjs - 下拉菜单中未触发单击事件
- javascript - 正则表达式检查字符串中的 3 个相同字母?
- visual-studio - 在 Visual Studio for Azure Analysis Services 模型中看不到表更新
- snowflake-cloud-data-platform - 您会将哪种类型的雪花连接器用于自动上传新数据的 IoT 数据?
- r - 正在使用哪个 plot()?