[英]I can not collect data from my json - React
我創建了一個菜單,包含子菜單和第三個孩子。 到目前為止,我只使用現在注釋的本地const數據中的json
完成了它。 我需要從現在起數據從我的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
屬性,因此您將空數組傳遞給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} />
)
}
}
不要使用componentWillMount
因為它已被棄用並且很快就會消失,正確的方法是在渲染中使用componentDidMount
方法以及狀態變量和測試。
this.state = {
navigation: [],
init: false
}
componentDidMount() {
fetch('json_menuFIN.php')
.then(response => response.json())
.then(data => {
this.setState({ navigation: data, init: true });
console.log( data)
})
}
此外,您無法從狀態中的navigation
變量中提取data
變量, navigation
已使用您的data
響應進行定義,因此請直接使用它。
render() {
const { navigation, init } = this.state;
if(!init) return null
return (
<Menu data={navigation}/>
)
}
我假設navigation
始終是一個數組,無論你用它做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.