我正在尝试使用redux
根据用户在react
中的位置动态创建菜单。
makeMenu
动作的reducer中有以下initialState:(整个reducer代码在帖子末尾(
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
您正在将url设置为this.props.state.makeMenu,而它是未定义的。您应该将url设置为this.props.state.