繁体   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