semantic-ui-react - Menu.Item点击触发组件渲染两次

问题描述 投票:0回答:1

学习反应和使用 semantic-ui-react Menu 建立一个SideBarMenu,并有以下问题。

  • 如何点击一个 Menu.Item 触发父组件(SBMenu) render 像render on component是由于以下原因而触发的 change in state or props 但是,SBMenu有什么变化?
  • 为什么SBMenu render 函数调用两次?
Rendering .... future
Rendering .... future

侧栏菜单

import React from 'react';
import { Sidebar, Menu, Segment, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import SBMenu from './SBMenu'
import './SidebarMenu.css';
import SBRoutes from './SBRoutes'


const menuItems = [
    { icon: 'dashboard', label: 'Future ITEM', name: 'future', url: '/future' },
    { icon: 'dashboard', label: 'Future ITEM1', name: 'future', url: '/future1' }
  ];

class SidebarMenu extends React.Component {
  constructor(props) {
    super(props);
    this.handleItemClick = this.handleItemClick.bind(this);
  }

  handleItemClick () {
      console.log('item clicked')
  }

  /*shouldComponentUpdate() {
    return true;
  }*/

  render() {
    console.log("SidebarMenu called....")

    return (
      <Sidebar.Pushable as={Segment} className="SidebarMenu">
        <Sidebar
          as={Menu}
          borderless
          animation="push"
          icon="labeled"
          inverted
          onHide={this.handleSidebarHide}
          vertical
          visible={true}
          width="thin"
        >

        <SBMenu menuItems={menuItems} />

        </Sidebar>
        <Sidebar.Pusher>
          <div className="container">
             <SBRoutes />
          </div>
        </Sidebar.Pusher>
      </Sidebar.Pushable>
    );
  }
}


export default SidebarMenu;

SBMenu

class SBMenu extends React.Component {

  constructor(props) {
    super(props);
  }


  render() {
    const {location,menuItems} = this.props;
    console.log("Rendering .... " + location.pathname)
    return (menuItems.map((item, index) => (
            <Menu.Item
            name={item.name}
            as={Link}
            to={item.url}
            active={location.pathname === item.url}
            data-menu={item.label}
            key={`menu_item_${index}`}
            >
                    <Icon name={item.icon} />
                    {item.label}
            </Menu.Item>
        ))
    );
  }
}

export default withRouter(SBMenu);
reactjs render semantic-ui-react
1个回答
0
投票

你可以使用提升状态来改变父组件的子状态。你可以简单地传递一个方法的SBMenu和工作。

SBMenu渲染两次,因为你在menuItems中使用相同的名称。

如果你改变menuItems的名称,现在应该可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.