我如何在没有Redux的情况下获得当前状态?

时间:2019-09-03 18:31:57

标签: javascript reactjs redux

我正在将redux与react一起使用,但我将redux保存为主要应用程序状态,并使用react钩子用于组件之间的非共享状态。

例如,我有一个导航栏菜单项,单击后每种颜色应变为蓝色,因此我决定转到 useState 来更改被单击的项并添加一个类 .active

我面临的问题是我没有得到最新状态,但是我得到了以前的状态,并且我知道react中的设置状态是异步的和成批的。

演示代码:

组件

 const [targets, getTarget] = useState([]);
 const addTarget = (e) => {
   getTarget([e.target]);
 }

 const handleOnItemClick = (e, category) => {
    addTarget(e);
    console.log(targets) // return [] on first click
 } 

myFunctionToAddAcTiveClass () {
  //i need to use state here but i could not
 // because it does not return the latest state
}

return(
 <ul className="categories-list-items d-flex justify-content-between mb-4">
      {items.map((item, index) => {
         return (
            <li
               key={index}
               onClick={(e) => handleOnItemClick(e, category)}
            >
             {item}
           </li>
         );
     })}
 </ul>
)

是否有一种方法可以在每次单击时添加正确的项目,以添加 .active 类?

0 个答案:

没有答案
相关问题