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

chore(docs): corrected react usage example #1012

Merged
merged 1 commit into from
Oct 19, 2024

Conversation

LanceMoe
Copy link
Contributor

非常好的项目,感谢作者!

我修正了react的使用例子。

原来的例子里:

    artalk.current = Artalk.init({
      el: container.current!,
      ...
    })

这里el传递值使用了TypeScript的非空断言,我认为这里的做法不是太好。

react的ref是支持函数传递的,使用函数传递也能避免使用useEffect。

可以参考下面的文章:

https://tkdodo.eu/blog/avoiding-use-effect-with-callback-refs

修改后如下:

const ArtalkComment = () => {
  const { pathname } = useLocation()
  const artalk = useRef<Artalk>()

  const handleContainerInit = useCallback(
    (node: HTMLDivElement | null) => {
      if (!node) {
        return
      }
      if (artalk.current) {
        artalk.current.destroy()
        artalk.current = undefined
      }
      artalk.current = Artalk.init({
        el: node,
        pageKey: pathname,
        pageTitle: document.title,
        server: 'http://localhost:8080',
        site: 'Artalk Blog',
        // ...
      })
    },
    [pathname],
  )

  return <div ref={handleContainerInit}></div>
}

希望对项目有帮助!

@qwqcode
Copy link
Member

qwqcode commented Oct 19, 2024

学习了,谢谢你的修改,这对项目很有帮助!❤️

@qwqcode qwqcode merged commit 15f2fb8 into ArtalkJS:master Oct 19, 2024
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants