Skip to content

useToggle提问 #2886

@JunlinZhu-Tommy

Description

@JunlinZhu-Tommy

问题

useToggledefaultValuereverseValue 作为 props 传入时,如果这些值发生变化,setLeftsetRight 仍然使用初始值。

示例代码

import { useToggle } from 'ahooks';
import { useState } from 'react';

function App() {
  const [parentValue, setParentValue] = useState('A');
  
  return (
    <div>
      <button onClick={() => setParentValue(parentValue === 'A' ? 'B' : 'A')}>
        切换: {parentValue}
      </button>
      <Child leftValue={parentValue} />
    </div>
  );
}

function Child({ leftValue }) {
  const [value, { setLeft }] = useToggle(leftValue, 'OFF');
  
  return (
    <div>
      <p>当前值: {value}</p>
      <p>leftValue prop: {leftValue}</p>
      <button onClick={setLeft}>setLeft</button>
    </div>
  );
}

复现步骤

  1. 点击 "切换" 按钮,parentValue 从 'A' 变为 'B'
  2. 点击子组件的 "setLeft" 按钮
  3. 期望:value 变为 'B'
  4. 实际:value 仍为 'A'(使用了初始值)

问题

这是预期的行为吗?如果需要响应动态 props 变化,应该如何处理?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions