简体   繁体   English

State 似乎未在重新渲染时更新

[英]State appears not to be updated on rerender

I have tried to build a simple side bar component where the clicked link has a class attribute of active .我尝试构建一个简单的侧边栏组件,其中单击的链接的 class 属性为active I have used useState to contain the ID of the clicked component as shown below, but the active link's class attribute is not being updated.我已使用useState来包含单击组件的 ID,如下所示,但活动链接的 class 属性未更新。 My understanding is that when I update the state via handleClick then a rerender should occur, and my newly built links should now have the correct class attributes as accessed via the state.我的理解是,当我通过handleClick更新 state 时,应该会发生重新渲染,并且我新建的链接现在应该具有正确的 class 属性,可通过 state 访问。 Why is this not working?为什么这不起作用?

import React, { useState } from 'react';
import { Link } from 'react-router-dom';

const SideBar = function () {

  const [activeLink, setActiveLink] = useState('nav-link-/');

  const linkConfig = [
    ['/', 'Home'],
    ['userAccount', 'Your Account'],
  ];

  const handleClick = (event) => {
    setActiveLink(event.target.getAttribute('id'));
  };

  const getLinkClass = (id) => {
    return id === activeLink ? 'active' : '';
  };

  const buildLinks = (config) => {
    return config.map((link) => {
      const id = `nav-link-${link[0]}`;
      return (<Link to={link[0]} key={link[0]}>
        <li id={id} className={getLinkClass(id)} onClick={handleClick}>
          {link[1]}
        </li>
      </Link>);
    });
  };

  return (
    <div className="side-bar">
      <ul>
        {buildLinks(linkConfig)}
      </ul>
    </div>
  );
};

export default SideBar;

It's a bit hard to guess, but on an EventTarget, there is no "setAttribute"-Property.有点难以猜测,但在 EventTarget 上,没有“setAttribute”-Property。 Try using "event.target.id" in the handleClick-Function.尝试在 handleClick-Function 中使用“event.target.id”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM