3

我想为反应钩子创建几个开源反应效果。例如,检查和更新用户代币余额的效果。

问题是:如何打包effect并创建一个模块,以便其他人使用?他们将如何导入和使用效果?

有什么最佳做法吗?

4

1 回答 1

2

您的钩子必须使用react 提供的“低级”钩子构建。不过,想出一个可重用/通用的身份验证钩子可能具有挑战性。

import {useState, useEffect} from 'react'
const useAuthentication = () => {
  const [user] = useState({}) // maybe shape of user.name, user.avatar, user.email ?
  useEffect(() => {
    // whatever
  })
  ...
  const login = ...
  const logout = ...
  return [user, login, logout]
}
export default useAuthentication


// a user of this hook
import useAuthentication from 'my-published-authentication-hook'
const Header = () => {
  [user, login, logout] = useAuthentication()
  return (
    // whatever login/logout button, user name, etc
  )
}
于 2018-11-19T09:33:42.277 回答