【问题标题】:I can not collect data from my json - React我无法从我的 json 中收集数据 - React
【发布时间】:2019-10-20 03:35:06
【问题描述】:

我创建了一个菜单,其中包含一个子菜单和第三个子菜单。到目前为止,我只是在本地 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>
}

我不知道还能做些什么来让它与我所拥有的一起工作。非常感谢您的帮助。

【问题讨论】:

  • 在你的渲染函数中将&lt;Menu data={data}/&gt;更改为&lt;Menu data={this.state.navigation}/&gt;
  • @Andrii Golubenko 如果我更改它,会出现以下错误:Can not read property 'map' of undefined

标签: javascript json reactjs


【解决方案1】:

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} />
        )
    }

}

【讨论】:

  • 是的,就是这样。对不起,您介意编辑您的答案并删除网址和服务器吗?非常感谢您所做的一切!
【解决方案2】:

不要使用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 始终是一个数组,无论你用它做什么。

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多