爲什麼我得到一個活的服務器上此錯誤:ReactJS - this.state。[object] .map不是函數嗎?
Uncaught TypeError: this.state.navitems.map is not a function
但我從來沒有在我的本地此錯誤。
的reactjs:
import React from 'react'; import $ from 'jquery';
import NavItem from './nav-item';
class Footer extends React.Component {
constructor(props) {
super(props);
this.state = {
navitems: [],
};
}
// Then fetch the data using $.get():
componentDidMount() {
this.serverRequest = $.get(this.props.source, function (result) {
this.setState({
navitems: result
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
var loop = this.state.navitems.map(function(item, index){
return <NavItem key={index} item={item}></NavItem>;
});
return (
<div>
<div className="nav">
<ul>{ loop }</ul>
</div>
</div>
)
} }
export { Footer as default }
任何想法如何,我可以解決這個問題?
編輯:
componentDidMount() {
console.log('props.source', this.props.source);
this.serverRequest = $.get(this.props.source, function (result) {
console.log('returned result', result);
this.setState({
navitems: result
});
}.bind(this));
}
結果:
props.source ./data/nav.json
returned result [{
"navId": "1",
"title": "Home",
"code": "home",
"href": null,
"style": null,
"sort": "1",
"url": "#",
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}, {
"navId": "2",
"title": "About",
"code": "about",
"href": null,
"style": null,
"sort": "2",
"url": "#",
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}, {
"navId": "3",
"title": "Contact",
"code": "contact",
"href": null,
"style": null,
"sort": "3",
"url": "contact",
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}]
感謝。我如何解決這個問題,如果它是由此引起的? – laukok
什麼是跨域請求問題btw? – laukok
如果它是由跨域「CORS」問題引起的,則需要在發送請求的服務器上設置正確的標頭。在請求上添加標頭'Access-Control-Allow-Origin:*'可能會起作用,但請注意,您並未打開服務器以應對意外的請求。 – casr