我正在尝试使用react
根据redux
中的用户位置动态创建菜单。
makeMenu
操作的化简器具有以下initialState :(整个化简器代码在文章末尾)
const initialState = {
current_url: url,
menu_urls: urls.filter(item => item !== url)
}
使用它并在组件中应用mapStateToProps
函数后,它可以正常工作:
const mapStateToProps = (state) => ({
state: state.makeMenu
})
因此在组件中,我已经使用this.props.state.makeMenu
访问了它的值,它也可以正常工作,并且在console.log(urls)
之后得到了以下结果:
{current_url: "", menu_urls: Array(4)}
current_url: ""
menu_urls: Array(4)
0: "edu"
1: "projects"
2: "skills"
3: "honors"
length: 4
__proto__: Array(0)
__proto__: Object
问题是当我想映射menu_urls来创建子菜单(代码中的Menu.Item
)时
import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Breadcrumb, Menu } from 'antd';
import { HomeOutlined } from '@ant-design/icons'
import { makeMenu } from '../../redux/actions'
import './navigation-ls.css';
class NavigationLS extends Component {
render() {
const urls = this.props.state.makeMenu
const menu = (
<Menu>
{console.log(urls)}
{
urls.menu_urls.map((url) =>
<Menu.Item>
<Link to={"/" + url}>
{url}
</Link>
</Menu.Item>
)
}
</Menu>
);
return (
<Fragment>
{console.log('hey')}
{console.log(this.props.state)}
<div className="nav">
<div className="pwd">
$PWD
</div>
<div className="breadcrumb">
<Breadcrumb>
<Breadcrumb.Item>
<HomeOutlined/>
</Breadcrumb.Item>
<Breadcrumb.Item overlay={menu}>
<Link to="/">
info
</Link>
</Breadcrumb.Item>
</Breadcrumb>
</div>
</div>
</Fragment>
)
}
}
const mapStateToProps = (state) => ({
state: state.makeMenu
})
export default connect(
mapStateToProps,
{ makeMenu }
)(NavigationLS)
正如我所说,console.log(urls)
可以正常工作,但是urls.menu_urls
不能正常工作。我已经阅读了关于stackoverflow的类似问题,但是它们都没有帮助。
编辑:
makeMenu 归约器:
import { MAKE_MENU } from '../actionTypes'
const urls = [
"",
"edu",
"projects",
"skills",
"honors",
]
const url = window.location.href.split("/")[3]
const initialState = {
current_url: url,
menu_urls: urls.filter(item => item !== url)
}
const makeMenu = (state = initialState, action) => {
switch(action.type) {
case MAKE_MENU: {
const { content } = action.payload
return {
current_url: content,
menu_urls: urls.filter(item => item !== content)
}
}
default:
return state
}
}
export default makeMenu
答案 0 :(得分:1)
您正在为this.props.state.makeMenu设置未定义的URL。您应该将网址设置为this.props.state。