首页 > 解决方案 > 如何在 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 不是函数。我的响应是对象类型,但我正在尝试使用地图。(肯定会出错)但不确定如何获取对象响应。任何人都可以帮助我。

标签: javascriptarraysreactjstypescript

解决方案


{Object.keys(this.state.dept).map((keyName, i) => (
    <li key={i}>
        <span>key: {i} Name: {this.state.dept[keyName].categories}</span>
    </li>
))}

推荐阅读