简体   繁体   English

使用 react/nextjs 中本地存储的参数初始化组件

[英]Initializing component with parameter from local storage in react/nextjs

I have a component provided by an external library which I need to provide an access token to.我有一个由外部库提供的组件,我需要提供一个访问令牌。 This access token is saved in localStorage at this point and I would like to read it and pass it to the component.此访问令牌此时保存在 localStorage 中,我想读取它并将其传递给组件。 This is my attempt using useEffect but this fails with the error {code: "initialization-error", error: "Access token required"}这是我使用useEffect的尝试,但失败并出现错误{code: "initialization-error", error: "Access token required"}

const test: NextPage = () => {
  const router = useRouter()
  let accessToken = ''
  useEffect(() => {
    const at = localStorage.getItem('accessToken')
    console.log(at) // prints out the correct access token
    if (at !== null) {
      accessToken = at
    }
  }, [])

  return (
      <WebSdk
        accessToken={accessToken}
        expirationHandler={() => Promise.resolve(accessToken)}
        onError={(error) => {
          console.log(error)
        }}
      />
  )
}

export default test

I'm guessing the useEffect hook runs after the component renderes - how can I read from local storage before or as the component renders?我猜 useEffect 钩子在组件渲染之后运行——如何在组件渲染之前或渲染时从本地存储中读取?

Since you are using nextjs you can't call the localStorage directly, so you have to check if the bowser has "initialized", something like this:由于您使用的是 nextjs,因此您不能直接调用 localStorage,因此您必须检查 bowser 是否已“初始化”,如下所示:

const test: NextPage = () => {
  const router = useRouter()
  const [initialized, setInitialized] = useState(false);
  const [accessToken, setAccessToken] = useState('');

  useEffect(() => {
    const at = localStorage.getItem('accessToken') || '';
    
    setInitialized(true);
    setAccessToken(at);
  }, [])
 
  if (!initialized) {
    return null;
  }  

  return (
      <WebSdk
        accessToken={accessToken}
        expirationHandler={() => Promise.resolve(accessToken)}
        onError={(error) => {
          console.log(error)
        }}
      />
  )
}

export default test

I'm guessing the useEffect hook runs after the component renderes我猜 useEffect 钩子在组件渲染后运行

Yes the component will render first before the hooks can be triggered, this is the equivalent of "componentDidMount" (if the hook's second parameter is empty) in early verions of react.是的,组件将在触发钩子之前首先呈现,这相当于早期版本的 react 中的“componentDidMount”(如果钩子的第二个参数为空)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM