javascript - 如何在 UI reactjs 中打印对象响应
问题描述
来自后端的响应是这样的:</p>
dept: Object { Sales: 33, Market: 12, Finance: 22, Hr: 26 }
模型.ts:
export default interface Dept{
categories: Record<string,number>;
}
零件:
interface State{
dept: Array<Dept>;
}
class MBA extends React.Component<Props & RouteComponentProps, State> {
state = {
dept: []
}
componentDidMount(){
this.service
.getCategories()
.then((dept) => {
this.setState(
{
...this.state,
dept: dept,
},
() => {
console.log(dept);
}
);
})
.catch((error) => {
console.log(error);
});
}
render(){
return (
{
this.state.dept.map((data: dept)=> {
<div>{dept.categories}</div>
}
}
)
}
service method:
getCategories(): Promise<Array<Dept>> {
return http
.get("https://localhost:8080/colleges")
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
在上面的代码中,我收到错误:this.state.dept.map 不是函数。我的响应是对象类型,但我正在尝试使用地图。(肯定会出错)但不确定如何获取对象响应。任何人都可以帮助我。
解决方案
{Object.keys(this.state.dept).map((keyName, i) => (
<li key={i}>
<span>key: {i} Name: {this.state.dept[keyName].categories}</span>
</li>
))}
推荐阅读
- amazon-web-services - AWS 资源消失
- nvidia - NVIDIA SDK Manager 无法在 Jetson Xavier NX 上安装
- python - Simultaneous reads of the same PyTorch torchvision.datasets object
- google-cloud-platform - 如何解决 Apache-Beam 中的 BeamDeprecationWarning
- html - 如何摆脱 CSS 中按钮之间不必要的空间
- node.js - mongodb 中是否有任何内置方法来更新 mongodb 文档中的数组
- drools - Drools 规则左侧的“this”等效关键字
- javascript - switch / if-elseif-else 函数是否应该有一个默认情况,如果在处理程序中没有匹配和处理的情况,则返回 null ?
- rust - 从 Rust BTreeMap 中删除一个范围
- arrays - 大型数组的基本 cuBLAS 点积返回不正确的值