当新值与旧值相同时,有没有办法触发 useState 挂钩

Is there a way to trigger useState hook when the newvalue is same as oldvalue

我有一个动画在 selectedName 更改时触发,但似乎新值与动画未触发的先前值相同。调查之后,钩子只触发新值不同于以前的值。有办法解决这个问题吗?

    const [selectedName, setSelectedName] = useState("");

  useEffect(() => {
    console.log("Change", selectedName)
  }, [selectedName]); 

https://codesandbox.io/s/reactts-text-animation-using-react-transition-group-64gum?file=/src/App.tsx

您的想法是正确的 - 即使数字相同,每次点击都会触发重新渲染。你做错的唯一一件事是在相同元素的每个渲染器上将相同的 key 道具分配给你的 CSSTransition 元素。

键必须是唯一的,因为 React 使用键 prop 来理解组件到 DOM 元素的关系,然后用于 reconciliation process。因此,密钥始终保持唯一非常重要,否则 React 很可能会混淆元素并改变不正确的元素。

无论如何,您确实需要第二个状态变量来触发重新渲染。我们将做一些基本的事情:const [trigger, triggerUpdate] = useState<boolean>(false);。然后你可以像这样触发它:triggerUpdate(!trigger);

当然,最重要的部分是 key prop

  return (
    <div className="App">
      <SwitchTransition mode="out-in">
        <CSSTransition<undefined>
          classNames="fade"
          addEndListener={(node: HTMLElement, done: () => void) => {
            node.addEventListener("transitionend", done, false);
          }}
          key={Math.random()
            .toString(36)
            .replace(/[^a-z]+/g, "")}
        >
          <h1 className="randomNumberText">{rndNumber}</h1>
        </CSSTransition>
      </SwitchTransition>
      <button onClick={() => getRandomNumber()}>Click Me!</button>
    </div>
  );

请注意,我使用此机制得出一个独特的 key,您不必一定要遵循此示例:

key={Math.random()
            .toString(36)
            .replace(/[^a-z]+/g, "")}

沙盒:https://codesandbox.io/s/reactts-text-animation-using-react-transition-group-forked-v2cm4?file=/src/App.tsx