簡體   English   中英

我無法從我的json收集數據 - React

[英]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屬性沒有titlemenu屬性,因此您將空數組傳遞給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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM