【问题标题】:ReactJS fetchAPI JSON type - TypeError: content.forEach is not a functionReactJS fetchAPI JSON 类型 - TypeError:content.forEach 不是函数
【发布时间】:2018-08-07 11:01:16
【问题描述】:

我将https://www.npmjs.com/package/react-metismenu 用于metismenu 并使用fetch api 从服务中获取响应。我得到了正确的响应,但低于异常

Warning: Failed prop type: Invalid prop `content` of type `object` supplied to `MetisMenu`, expected an array
TypeError: content.forEach is not a function

服务代码:

@GET
    @Path("/menu")
    @Produces(MediaType.APPLICATION_JSON)
    public String getMenuItems(@QueryParam("industry") String industry) {
        JSONArray response = new JSONArray();
        try{
            org.json.JSONObject obj = new org.json.JSONObject();
            obj.put("icon", "spinner");
            obj.put("label", "User Maintenance");
            obj.put("to", "#a-link");
            response.put(obj);

            org.json.JSONArray content = new org.json.JSONArray();
            obj = new org.json.JSONObject();
            obj.put("icon", "apple");
            obj.put("label", "System Controls");
            obj.put("to", "#b1-link");
            content.put(obj);
            obj = new org.json.JSONObject();
            obj.put("icon", "user");
            obj.put("label", "User Maintenance");
            obj.put("to", "#b2-link");
            content.put(obj);

            obj = new org.json.JSONObject();
            obj.put("icon", "gear");
            obj.put("label", "System Preferences");
            obj.put("content", content);            
            response.put(obj);

            obj = new org.json.JSONObject();
            obj.put("icon", "gear");
            obj.put("label", "Configuration");
            obj.put("to", "#c-link");
            response.put(obj);
        }
        catch(Exception e){

        }
        return response.toString();
    }

和 index.js 代码:

var content=fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc').then(function(response){
         return response
});
ReactDOM.render(
  <MetisMenu content={content} activeLinkFromLocation />,
  document.getElementById('root')
);

如果我对 const 值进行硬编码,那么它可以正常工作。

得到它的工作,问题是 CORS,所以我在我正在使用的其他应用程序的 web.xml 中避免使用 CORS。并用以下部分更改了代码:

export default class MenuComponent extends Component {
  constructor() {
    super();
    this.state = {}
  }

componentDidMount(){
  fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
  .then(response => response.json())
  .then(parsedJSON => parsedJSON.data.map(menu => (
    {
      to: `${menu.to}`,
      icon: `${menu.icon}`,
      label: `${menu.label}`
      // content: `${menu.content}`
    }
  )))
  .then(content => this.setState({
    content
  }))
}

  render() {
    console.log('333');
    console.log(this.state.content);
    return (
      <MetisMenu content={this.state.content} activeLinkFromLocation />
    )
  }
}

现在唯一的问题是内容中的嵌套内容不起作用,任何人都可以帮助我。 我也试过https://github.com/alpertuna/react-metismenu中提到的ajax,也没用。

【问题讨论】:

  • 看起来你的响应是一个对象,而不是一个数组
  • 当我在浏览器上点击服务时,它会返回正确的 jsonarray,而我在 reactjs 中尝试了 console.log() 然后它在很多对象中显示 promise 对象跨度>

标签: reactjs metismenu


【解决方案1】:

由于fetch 返回一个承诺,您需要等待它使用Promise.thenawait 方法解决。

var content = await fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc');

我建议你将这个获取代码包装在一个单独的组件中,并将响应传递给 setState 方法。

SomeComponent.js:

import React, { Component } from 'react'

export default SomeComponent extends Component {
  constructor() {
    this.state = {
      content: []
    }
  }
  
  componentDidMount() {
    fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
    .then((response) => this.setState({ content: response }));
  }
  
  render() {
    return (
      <MetisMenu content={this.state.content} activeLinkFromLocation />
    )
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

index.js:

import SomeComponent from './SomeComponent';
    
ReactDOM.render(
  <SomeComponent />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

【讨论】:

  • 谢谢,这没有引发错误,但页面中仍然没有加载数据。当我记录来自服务的响应时,它将内容显示为空数组
  • 你是否像这样记录响应:componentDidMount() { fetch('localhost:8084/Accounting/rest/v1/company/menu?request=abc') .then((response) => { console.log(response); this.setState({ content: response })); }
  • componentDidMount() { fetch('localhost:8084/Accounting/rest/v1/company/menu?request=abc') .then((response) => this.setState({ content: response }));控制台.log(this.state.content); }
  • 您在控制台中看到空数组是正确的。由于this.setState 是 acync,因此内容的新值不会应用于状态。尝试将console.log(this.state.content) 放入render 方法中。
  • 结果是同一个空数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 2018-01-02
  • 2021-12-01
  • 1970-01-01
  • 2021-01-13
  • 2015-10-29
相关资源
最近更新 更多