我正在使用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 ,它也没有用。