简体   繁体   English

反应组件不刷新 state 上的内容更改 [Next.js]

[英]React component not refreshing content on state change [Next.js]

So i have the problem that my Header component is not changing content on state change.所以我的问题是我的 Header 组件没有更改 state 更改的内容。 I want to display user Profile when state changes, but unfortunately it doesn't change content immediately, but it does after page refresh/route.push to other page.我想在 state 更改时显示用户Profile ,但不幸的是它不会立即更改内容,但它会在页面刷新/route.push 到其他页面之后发生。

Here is the function i fetch data with.这是我用来获取数据的 function。 It triggers when URL query have code param to finish auth flow and then fetch data, or when access token is already in local storage then it just fetches data.它在 URL 查询具有code参数以完成身份验证流程然后获取数据时触发,或者当访问令牌已经在本地存储中时它只是获取数据。

export default function Header(props) {
const userProfile = async() => { 
    if (query.code && !userId) { 
      await handleAuthuser();
      const { profile, balance, userStatus } = await getUserData();
      setMoneyButtonData(profile, balance, userStatus);
    }

    if (storage.getItem('mb_js_client:oauth_access_token') && !userId) {
      const { profile, balance, userStatus } = await getUserData();
      setMoneyButtonData(profile, balance, userStatus);
    } 
  }
  userProfile();
function setMoneyButtonData(_profile, _balance, _userStatus) {
    setUserId(_profile.id);
    ...
  }

Then i have condition in function component return :然后我在 function 组件return条件:

<a>
 {!userId ? <LoginDialog /> :
  <Profile name={userName} userId={userId} primaryPaymail={userPrimaryPaymail} userEmail={userEmail} userAvatar={userAvatarUrl} userAmount={userAmount} userCurrency={userCurrency} userStatus={userStatus}/> }
</a>

I tried using useEffect() , i tried setTimeout but it didn't work.我尝试使用useEffect() ,我尝试了setTimeout但它没有用。 I think it have something to do with client/server side rendering.我认为这与客户端/服务器端渲染有关。 What can i do to fetch this data before component render and display it?在组件渲染和显示之前我能做些什么来获取这些数据?

you can use react hook useEffect你可以使用反应钩useEffect

  useEffect( async()=>{

    if (query.code && !userId) { 
       await handleAuthuser();
       const { profile, balance, userStatus } = await getUserData();
       setMoneyButtonData(profile, balance, userStatus);
    }

    if (storage.getItem('mb_js_client:oauth_access_token') && !userId) {
        const { profile, balance, userStatus } = await getUserData();
        setMoneyButtonData(profile, balance, userStatus);
    } 
  }
},[])

It will automatically work when your jsx is load.当你的 jsx 加载时,它会自动工作。

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

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