我创建了一个菜单,其中包含一个子菜单和第三个子菜单。到目前为止,我只是用一个 json
在本地 const 数据中完成了它,现在已经注释掉了。我需要从现在开始从我的 json 中收集数据,但我不知道该怎么做。现在我收到以下错误:'data' is not defined
(在我的渲染中)
class Nav extends Component {
constructor(props){
super(props)
this.state = {
navigation:[]
}
}
componentWillMount() {
fetch('json_menuFIN.php')
.then(response => response.json())
.then(data =>{
this.setState({navigation: data });
console.log( data)
})
}
render(){
const { data = null } = this.state.navigation;
if ( this.state.navigation && !this.state.navigation.length ) { // or wherever your data may be
return null;
}
return (
<Menu data={this.state.navigation}/>
)
}
}
const renderMenu = items => {
return <ul>
{ items.map(i => {
return <li>
<a href={i.link}>{ i.title }</a>
{ i.menu && renderMenu(i.menu) }
</li>
})}
</ul>
}
const Menu = ({ data }) => {
return <nav>
<h2>{ data.title }</h2>
{ renderMenu(data.menu) }
</nav>
}
我不知道还能做什么才能让它与我现有的一起工作。非常感谢您的帮助。
最佳答案
您在 state
中的 navigation
属性没有 title
和 menu
属性,因此您将一个空数组传递给菜单
组件。这就是为什么出现错误 Cannot read property 'map' of undefined
的原因。您应该在 constructor
中更改状态初始化。
class Nav extends Component {
constructor(props){
super(props);
this.state = {
navigation: {//<-- change an empty array to object with a structure like a response from the server
menu: [],
title: ''
}
}
}
//...
render(){
return (
<Menu data={this.state.navigation} />
)
}
}
关于javascript - 我无法从我的 json 中收集数据 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446686/