import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Container } from './styles';
import { MdContentCopy, MdGroup, MdPerson, MdMovie, MdSettings } from 'react-icons/md';
const items = [
{
route: '/',
icon: <MdContentCopy />,
title: 'Orders',
},
{
route: '/customers',
icon: <MdGroup />,
title: 'Customers',
},
{
route: '/movies',
icon: <MdMovie />,
title: 'Movies',
},
{
route: '/settings',
icon: <MdSettings />,
title: 'Settings',
},
{
route: '/Profile',
icon: <MdPerson />,
title: 'Profile',
},
];
class ItemList extends Component {
state = {
active: false,
};
render() {
const { open, history } = this.props;
const pathName = history.location.pathname;
return (
<Container open={open} active={this.state.active}> // PASSING ACTIVE PROPS TO STYLED COMPONENT
{items.map((item, index) => {
if (item.route === pathName) this.setState({ active: true }); // THIS THROWS AN ERROR BECAUSE TOO MANY RE-RENDERS
return (
<Link to={item.route} key={index}>
{item.icon}
<span>{item.title}</span>
</Link>
);
})}
</Container>
);
}
}
export default ItemList;
我正在尝试将活动道具传递给循环内的样式化组件(容器)。我尝试使用setState触发重新渲染,因为如果我只分配一个变量(让active = false,并且如果if语句为true,那么active = true)将不会重新渲染组件,而active始终为false 。但是循环内的setState会产生大量重新渲染,并引发深度超出错误。关于如何执行此操作的任何想法?
答案 0 :(得分:1)
在此用例中无需设置状态(使用item.route === pathName代替this.state.active),只需将有效值true或false传递给组件,这是下面提到的修订类。
但是在此用例中,匹配一条路由将作为active = true传递到容器。
class ItemList extends Component {
render() {
const { open, history } = this.props;
const pathName = history.location.pathname;
const isActive = items.filter(item => item.route === pathName).length > 0;
return (
<Container open={open} active={isActive}> // PASSING ACTIVE PROPS TO STYLED COMPONENT
{items.map((item, index) => {
return (
<Link to={item.route} key={index}>
{item.icon}
<span>{item.title}</span>
</Link>
);
})}
</Container>
);
}
}
答案 1 :(得分:0)
我已经复制了您的render方法,在此更改了概念。只是我已经在render方法中检查了activeStatus并通过了它。对于任何状态更改,都将调用render,然后它将重新制作activeStatus。
render() {
const { open, history } = this.props;
const pathName = history.location.pathname;
//code here to check the pathName
let activeStatus = (items.filter(item => item.route == pathName) || []).length > 0 ? true : false;
return (
<Container open= { open } active = { activeStatus } >
{
items.map((item, index) => {
return (
<Link to= { item.route } key = { index } >
{ item.icon }
< span > { item.title } < /span>
< /Link>
);
})
}
</Container>
);
}