topNavigation.js
import React, { Component } from 'react';
import axios from 'axios';
import SubMenu from './subMenu';
class Navigation extends Component {
state = {
mainCategory: []
}
componentDidMount() {
axios.get('http://localhost:3030/topCategory')
.then(res => {
console.log(res.data.express);
this.setState({
mainCategory: res.data.express.catalogGroupView
})
})
}
render() {
const { mainCategory } = this.state;
return mainCategory.map(navList => {
return (
<ul className="header">
<li key={navList.uniqueID}> <button className="dropbtn ">{navList.name}</button>
<SubMenu below={this.props.navList.catalogGroupView}/>
</li>
</ul>
)
})
}
}
export default Navigation;
我是新来的反应者,正试图建立一个电子商务网站。我设计了主页。对于导航,我使用了外部API http://149.129.128.3:3737/search/resources/store/1/categoryview/@top?depthAndLimit=-1,-1,-1,-1
并映射响应。
如果我使用以下代码代替 SubMenu组件有效
<ul>
{console.log(navList.catalogGroupView)}
{
navList.catalogGroupView.map(sub=> {
return <li key={sub.uniqueID}> <button>{sub.name}</button></li>
})
}
</ul>
但是根据url端点响应,有更多子类别无法映射。
我想创建一个单独的组件来显示子菜单项。但是,每当我使用此代码时,它都将无效。
Submenu.js组件
import React, { Component } from 'react';
class SubMenu extends Component {
constructor(props) {
super(props);
this.state = {
subCategory: []
};
}
render() {
return subCategory.map(sub => {
return (
<ul>
<li key={sub.uniqueID}> <button>{sub.name}</button></li>
</ul>
)
})
}
}
export default SubMenu;
有人可以帮我这个忙吗?我会很感激。我没弄错我的地方。
答案 0 :(得分:1)
您正在尝试访问状态子类别。这是工作部分:
import React, { Component } from 'react';
class SubMenu extends Component {
constructor(props) {
super(props);
this.state = {
subCategory: []
};
}
render() {
const { subCategory } = this.state; // you should've add this part
return subCategory.map(sub => {
return (
<ul>
<li key={sub.uniqueID}> <button>{sub.name}</button></li>
</ul>
)
})
}
}
export default SubMenu;
更新 在这里:
<SubMenu below={this.props.navList.catalogGroupView}/>
您正在尝试访问不存在的prop,因此您应该这样做:
<SubMenu below={navList.catalogGroupView}/>
然后在子菜单中,应映射道具,而不是状态,因为状态始终为空数组(因为未设置状态)。在那种情况下,您不需要使用状态,因为您只需要遍历数组。这是Submenu的代码:
import React, { Component } from 'react';
class SubMenu extends Component {
render() {
const {below} = this.props;
return below.map(sub => {
return (
<ul>
<li key={sub.uniqueID}> <button>{sub.name}</button></li>
</ul>
)
})
}
}
export default SubMenu;
topNavigation.js的理论上可行的代码:
import React, { Component } from 'react';
import axios from 'axios';
import SubMenu from './subMenu';
class Navigation extends Component {
state = {
mainCategory: []
}
componentDidMount() {
axios.get('http://localhost:3030/topCategory')
.then(res => {
console.log(res.data.express);
this.setState({
mainCategory: res.data.express.catalogGroupView
})
})
}
render() {
const { mainCategory } = this.state;
return mainCategory.map(navList => {
return (
<ul className="header">
<li key={navList.uniqueID}> <button className="dropbtn ">{navList.name}</button>
<SubMenu below={navList.catalogGroupView}/>
</li>
</ul>
)
})
}
}
export default Navigation;
希望这会有所帮助。