Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useValueMutation #2622

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

FanetheDivine
Copy link

[中文版模板 / Chinese template]

🤔 This is a ...

  • New feature
  • Bug fix
  • Site / documentation update
  • Demo update
  • TypeScript definition update
  • Bundle size optimization
  • Performance optimization
  • Enhancement feature
  • Internationalization
  • Refactoring
  • Code style optimization
  • Test Case
  • Branch merge
  • Other (about what?)

🔗 Related issue link

💡 Background and solution

修复上次pr中此hook存在的bug
在开发中经常遇到这样的需求:受控组件要防抖地进行更新.这个hook可以解决这个问题.

const InputWithMutation: FC<{ value: string; onChange: (newVal: string) => void }> = (props) => {
  const [value, onChange] = useValueMutation(props.value, props.onChange);
  return <input value={value} onChange={(e) => onChange(e.target.value)} />;
};

InputWithMutation可以在受控的同时接受一个经过防抖处理的onChange作为参数

const Demo1: FC = () => {
  const [text, setText] = useState('');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'start' }}>
      <button onClick={() => setText(Math.random().toString(36).slice(2))}>mutate</button>
      {text}
      <InputWithMutation value={text} onChange={debounce(setText, 1000)} />
    </div>
  );
};

现在可以在输入框内自由输入 同时在text突变的时候控制输入框内的值
相比useControllableValue,这个钩子允许组件在受控/非受控间自由切换而不需要对value做特殊处理,也可以用于防抖、transition等异步更新情形 参考https://codesandbox.io/p/devbox/test-usevaluemutation-nfcnk3

📝 Changelog

Language Changelog
🇺🇸 English add hook useValueMutation
🇨🇳 Chinese 增加钩子useValueMutation

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • TypeScript definition is updated/provided or not needed
  • Changelog is provided or not needed

FanetheDivine and others added 3 commits August 3, 2024 18:20
使用isUncontrolledRef判断组件是否处于非受控状态 避免因上级组件更新而导致结果错误
更新测试用例
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant