我正在构建一个带有类别和子类别的水平菜单的页面,以使用react和react-bootstrap填充数据库数据。
数据库表(即levels
)具有以下结构:
id | level_name | category | subcategory | parent_id
如果该行用于category
thensubcategory
并且parent_id
具有值0
并category
包含1
。如果该行用于子类别,则category
列包含0
、subcategory
包含1
和parent_id
具有id
该类别的子类别。
在使用子类别作为下拉项构建类别的水平菜单时,我遍历数据库表,当我得到一行中的值为零时parent_id
,我选择该id
值并再次遍历表以查找子类别。
为简单起见,您可以只专注于map
两次使用的函数。这就是问题发生的地方。
我的 reactJS 代码是:
class Header extends Component {
constructor (props) {
super(props)
this.state = {
levels_all:[],
cat_id_found:0,
cat_name:''
}
}
componentDidMount(prevProps) {
//levels_all gets the value through an ajax call with axios here
this.setState({
levels_all: levels_all
})
}// end of componentDidMount
render () {
var cat_id_found=0;
var cat_name = '';
return (
<>
<nav className='navbar navbar-expand-md navbar-light navbar-laravel'>
<div className='container'>
<Link className='navbar-brand' to='/'>Tasksman</Link>
</div>
</nav>
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">Link</Nav.Link>
{
this.state.levels_all.map( (item, idx) => ( item.parent_id == 0 ?
(
cat_id_found=item.id,
cat_name = item.level_name
<NavDropdown title="Dropdown1111" id="basic-nav-dropdown">
this.state.levels_all.map( (item1, idx) =>
(
cat_id_found == item1.id ? (
<NavDropdown.Item href="#action/3.1">item1.level_name</NavDropdown.Item>
):(
)
))
</NavDropdown>
) : (
)
))
}
</Nav>
</Navbar.Collapse>
</Navbar>
<h1>THIS IS HEADER </h1>
</>
)
}
}
export default Header
但是我在运行命令时在命令提示符中收到以下错误npm run watch
:
Header.js: Unexpected token, expected "," 表示在行的末尾title
-
<NavDropdown title="Dropdown1111" id="basic-nav-dropdown">.
如何摆脱错误?
编辑:
我有ComponentDidMount
这样的:
componentDidMount(prevProps) {
axios
.post('/api/fetchLevels')
.then(response => {
// redirect to the homepage
//history.push('/')
console.log("header response = ");
console.log(response);
var levels_all = response.data.result;
this.setState({
levels_all: levels_all
})
})
.catch(error => {
this.setState({
// errors: error.response.data.errors
errors: error
})
})
}// end of ComponentDidMount