【问题标题】:Display the specfied list in frontend在前端显示指定列表
【发布时间】:2021-04-04 06:17:32
【问题描述】:

目标:
在前端显示 listGetAllIndustry 的内容。

问题:

"Error: Objects are not valid as a React child (found: object with keys {listGetAllJobAdvertisement, listGetAllLocation, listGetAllIndustry}). If you meant to render a collection of children, use an array instead."

为了在前端显示 listGetAllLocation 的内容,我遗漏了哪部分代码?

信息:
*我是 React JS 新手

谢谢!


{"listGetAllJobAdvertisement":[],"listGetAllLocation":[{"locationId":1,"city":"LOS ANGELES","country":"USA"},{"locationId":2,"city":"LONDON","country":"ENGLAND"},{"locationId":3,"city":"BERLIN","country":"GERMANY"}],"listGetAllIndustry":[{"industryId":1,"name":"ENERGY"},{"industryId":2,"name":"MATERIALS"},{"industryId":3,"name":"INDUSTRIALS"},{"industryId":4,"name":"CONSUMER STAPLES"},{"industryId":5,"name":"HEALTH CARE"},{"industryId":6,"name":"FINANCIALS"},{"industryId":7,"name":"INFORMATION TECHNOLOGY"},{"industryId":8,"name":"COMMUNICATION SERVICES"},{"industryId":9,"name":"UTILITIES"},{"industryId":10,"name":"REAL ESTATE"}]}

import { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { VacantPositions } from '../../src/contexts/api';

class Open extends Component {
  state = { aaa: [] };

  componentDidMount() {
      fetch(VacantPositions)
      .then(results => results.json())
      .then(data => this.setState({ aaa: data }  ))
      .catch(err => console.log(err))
  }
  render() {
    return (
      <div>
      { this.state.aaa}
      </div>
    );
  }
}

export default Open;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您会看到此错误,因为您在 render 函数的 return 语句中直接使用状态变量 aaa 而没有告诉 react 如何将 aaa 变量转换为 JSX。

    我已包含 aaa 和另外 1 个变量 bbb。根据您的需要,您可以保留 1 个变量,从您的 Open 组件中删除另一个及其相应的用法。

    import { Component } from "react";
    import { BrowserRouter as Router, Route, Link } from "react-router-dom";
    
    class Open extends Component {
      state = {
        // state variable should be object if api response is object
        aaa: {},
        // if you only store 'listGetAllIndustry' then state variable should be array
        bbb: []
      };
    
      componentDidMount() {
        // I am assuming the api response to be this
        const data = {
          listGetAllJobAdvertisement: [],
          listGetAllLocation: [
            { locationId: 1, city: "LOS ANGELES", country: "USA" },
            { locationId: 2, city: "LONDON", country: "ENGLAND" },
            { locationId: 3, city: "BERLIN", country: "GERMANY" }
          ],
          listGetAllIndustry: [
            { industryId: 1, name: "ENERGY" },
            { industryId: 2, name: "MATERIALS" },
            { industryId: 3, name: "INDUSTRIALS" },
            { industryId: 4, name: "CONSUMER STAPLES" },
            { industryId: 5, name: "HEALTH CARE" },
            { industryId: 6, name: "FINANCIALS" },
            { industryId: 7, name: "INFORMATION TECHNOLOGY" },
            { industryId: 8, name: "COMMUNICATION SERVICES" },
            { industryId: 9, name: "UTILITIES" },
            { industryId: 10, name: "REAL ESTATE" }
          ]
        };
        // fetch(VacantPositions)
        // .then(results => results.json())
        // .then(data => this.setState({ aaa: data }  ))
        // .catch(err => console.log(err))
    
        this.setState({
          // keeping complete api response in the state
          aaa: data || {},
          // keeping only 'listGetAllIndustry' from api response in the state
          bbb: data.listGetAllIndustry || []
        });
      }
      render() {
        return (
          <div>
            {this.state.aaa.listGetAllIndustry &&
              this.state.aaa.listGetAllIndustry.map((industry) => {
                return (
                  <div key={industry.industryId}>
                    <span>{industry.industryId}.</span> &nbsp;
                    <span>{industry.name}</span>
                  </div>
                );
              })}
            ===================================
            {this.state.bbb.map((industry) => {
              return (
                <div key={industry.industryId}>
                  <span>{industry.industryId}.</span> &nbsp;
                  <span>{industry.name}</span>
                </div>
              );
            })}
          </div>
        );
      }
    }
    
    export default Open;
    

    【讨论】:

      【解决方案2】:

      您的 api 正在返回具有多个键和值的对象,您将该对象设置为称为 'aaa' 的状态,因此您不能直接在返回部分呈现对象,您只能在返回方法中呈现特定值.您可以使用 object.entries.map

      {Object.keys(this.state.aaa).map(function(key, index) {
       return (
      <p>{key}</p>
      <p>{index}</p>
      )
      })};
      

      或者您可以指定特定的值,例如

      render() {
      return (
        <div>
        { this?.state?.aaa?.listGetAllLocation[0]?.city}
        </div>
      );}
      

      【讨论】:

      • 感谢您的帮助!当我使用“ { this?.state?.aaa?.listGetAllLocation[0]?.city} ”时,我收到错误消息“TypeError: Cannot read property '0' of undefined”
      • { this?.state?.aaa?.listGetAllLocation?.[0]?.city} 检查这个?
      • "{ this?.state?.aaa?.listGetAllLocation?.[0]?.city}" 有效并且控制台中没有错误显示。前端没有显示数据
      • 我猜有些格式问题会导致控制台检查 aaa 是数组还是对象 render() { return ( &lt;div&gt; {console.log( this?.state?.aaa)} &lt;/div&gt; );}
      • "return (
        {console.log( this?.state?.aaa)}
        );}" 不显示数据。请看图(内容更新)
      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2013-09-15
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      相关资源
      最近更新 更多