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

当前的usePrevious实现违反了useRef的使用准则的。 #780

Closed
heroboy opened this issue Dec 9, 2020 · 4 comments
Closed

当前的usePrevious实现违反了useRef的使用准则的。 #780

heroboy opened this issue Dec 9, 2020 · 4 comments
Assignees
Labels

Comments

@heroboy
Copy link

heroboy commented Dec 9, 2020

在render中不能读写current。除了,这种模式:

if (!ref.current)
{
    ref.current = 123;
}

facebook/react#18545

@awmleer
Copy link
Collaborator

awmleer commented Dec 9, 2020

React 官网文档上提供了另一种实现思路
可能会优雅一些

但是我觉得我们现在的 usePrevious 实现其实是没有鲁棒性问题的,因为 prevRefcurRef 都没有暴露给外部,是完全可控的,而且也没有异步逻辑

@heroboy
Copy link
Author

heroboy commented Dec 10, 2020

请看这个示例:
https://codesandbox.io/s/wizardly-platform-we6q2?file=/src/App.js
在StrictMode下有了不同的行为。
我不知道这样会不会对以后concurrent mode有影响。concurrent mode下会有很多render但是不commit的情况。但是好像这种render但不commit的情况下,对ref.current的设置是无效的。

function Content() {
  const [v, setV] = useState(0);
  const p0 = usePrevious(v);
  const p1 = usePrevious(p0);
  const p2 = usePrevious(p1);
  return (
    <>
      <div>
        <button onClick={() => setV(v + 1)}>+1</button>
      </div>
      <div>
        {p0},{p1},{p2}
      </div>
    </>
  );
}

@awmleer
Copy link
Collaborator

awmleer commented Dec 10, 2020

@heroboy 嗯嗯的确复现出来了……

而且我试了一下,如果用 React 官方文档上的 usePrevious 实现的话,StrictMode 下是也正常的行为
cc @brickspert

@brickspert
Copy link
Collaborator

Hello:

这个问题我们已经在 v3.0 版本彻底修复,目前 v3.0 版本已经发布 alpha 版本。

欢迎试用。

文档:https://ahooks-next.surge.sh/
源码:https://github.com/alibaba/hooks/tree/next

安装最新分支

$ npm install --save ahooks@next
# or
$ yarn add ahooks@next

We have fixed this problem in the v3.0 version, and the alpha has been released.

Welcome to try.

Doc:https://ahooks-next.surge.sh/
Source Code:https://github.com/alibaba/hooks/tree/next

Install v3.0

$ npm install --save ahooks@next
# or
$ yarn add ahooks@next

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants