javascript - 我无法从我的 json 中收集数据 - React

标签 javascript json reactjs

我创建了一个菜单,其中包含一个子菜单和第三个子菜单。到目前为止,我只是用一个 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 属性没有 titlemenu 属性,因此您将一个空数组传递给菜单 组件。这就是为什么出现错误 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/

相关文章:

javascript - 背景图像下方的白色区域

Json4s 在序列化期间忽略 None 字段(而不是使用 'null' )

javascript - 将 JSON 解析为对象数组时陷入 while 循环

javascript - 在动态加载的 es 模块中使用 React

android - 在 React Native 中设置 React-Native-Paper 组件的样式

javascript - Shopify:结合 HTML 和 JavaScript

javascript - 如何将标签保留在可调整大小和可滚动的 div 内的一个位置?

javascript - 未捕获的类型错误 : Cannont set Property 'valueAsDate' of null

javascript - 迭代 Backbone 中的模型属性?

javascript - 本地 React 构建有效,但服务器构建 js css 文件时出现错误 404。如何让包裹正确构建路径?