简体   繁体   中英

next.js code works in run dev but not run build

The problem is with the useAddress() funciton in run dev when console logged it returns undefined undefiuned then address however in the run build/start it just returns undefined. How do I go about fixing this.

 import { useAddress } from "@thirdweb-dev/react"; import Head from 'next/head'; import Link from 'next/link'; import Username from '../components/Username'; import React from "react"; const Home = () => { let address = useAddress(); console.log(address) if (address) { return ( <> <Head> <title>home</title> <link rel="icon" href="/drum.svg" /> </Head> <Username address={address} /> </> ); } else { return ( <> <Head> <title>home</title> <link rel="icon" href="/drum.svg" /> </Head> <Link href="/"> <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a> </Link> </> ); } } export default Home;

Imperative code is too unpredictible in React. You should use useEffect(()=>{console.log(address)},[]) instead and it will probably work the same in both settings.

I hope this works:

import { useAddress } from "@thirdweb-dev/react";
import Head from 'next/head';
import Link from 'next/link';
import Username from '../components/Username';
import React, {useState, useEffect} from "react";

const Home = () => {
    const [address, setAddress] = useState(false)

    useEffect(()=> {
        setAddress(useAddress())
    }, [])

   
    
        if (address) {
            return (
                <>
                    <Head>
                        <title>home</title>
                        <link rel="icon" href="/drum.svg" />
                    </Head>
                    <Username address={address} />
                </>
            );
        } else {
            return (
                <>
                    <Head>
                        <title>home</title>
                        <link rel="icon" href="/drum.svg" />                
                    </Head>
                    <Link href="/">
                    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a>
                    </Link>
                </>
            );
        }
}

export default Home;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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