gpt4 book ai didi

javascript - 如何将 Prop 传递给循环内的样式化组件

转载 作者:行者123 更新时间:2023-11-30 19:02:14 26 4
gpt4 key购买 nike

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;

我正在尝试将事件 Prop 传递给循环内的样式化组件(容器)。我尝试使用 setState 来触发重新渲染,因为如果我只是分配一个变量(让 active = false 并且如果 if 语句为真则 active = true)它不会重新渲染组件并且 active 将始终为 false .但是循环内的 setState 会进行大量重新渲染并抛出深度超出错误。关于如何执行此操作的任何想法?

最佳答案

在此用例中无需设置状态(使用 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>
);
}

关于javascript - 如何将 Prop 传递给循环内的样式化组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com