简体   繁体   English

React Hook useEffect 多个问题

[英]React Hook useEffect multiple problems

This is my first time using a useEffect hook.这是我第一次使用 useEffect 钩子。 what its doing is reading the database to see if a value returns and if a value returns thats the userToken which is sign of an account so it signs you in. However, I have 2 problems.它所做的是读取数据库以查看是否返回值以及是否返回值,这就是用户令牌,它是帐户的标志,因此它会登录。但是,我有两个问题。 The Link name button doesnt automatically sign you in, instead you have to type another letter in the input box after to sign in. I tried fixing this by adding connectUser under writeUserData on line 49 but that just makes the site crash.链接名称按钮不会自动让您登录,而是您必须在登录后在输入框中键入另一个字母。我尝试通过在第 49 行的 writeUserData 下添加 connectUser 来解决此问题,但这只会使网站崩溃。 My second problem is I cant display {userToken} on the page after bewing signed in. I recieve Error: Objects are not valid as a React child (found: object with keys {username}).我的第二个问题是登录后我无法在页面上显示 {userToken}。我收到错误:对象作为 React 子项无效(找到:带有键 {username} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

 import React, { useState, useEffect } from "react"; import {initializeApp} from 'firebase/app'; import { getDatabase, ref, set, child, get} from 'firebase/database'; export default function Username(props) { const [userName, setUsername] = useState(''); const [userToken, setuserToken] = useState('') const clientCredentials = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, } const app = initializeApp(clientCredentials); const db = getDatabase(); const address = props.address; function writeUserData(userId, userN, ) { const reference = ref(db, 'users/' + userId); set(reference, { username: userN, }); } const dbRef = ref(getDatabase()); function connectUser() { get(child(dbRef, `users/${address}`)).then((snapshot) => { if (snapshot.exists()) { setuserToken(snapshot.val()); } else { console.log("No data available"); } }).catch((error) => { console.error(error); }); } const handleChange = (event) => setUsername(event.target.value); function handleClick(e) { writeUserData( address, userName); } useEffect(() => { connectUser() }); while (userToken == '') return ( <> <div> <p className = "account-Info" >address: {address}</p> </div> <div id="form"> <h2 className='user-Create' > Username </h2> <form id='set-User'> <input id='username' className="user-Create" type='text' value={userName} onChange={handleChange} required minLength='3' maxLength='30' pattern="[a-zA-Z0-9_]+" title='only letters, numbers, and underscores.'/> <button className='user-Create' type="button" onClick={handleClick}>Link Name</button> </form> </div> </> ); while (userToken) return ( <p className = "account-Info" >hi user</p> ); }

First, please do not use while .首先,请不要使用while Instead, use if .相反,使用if

if (!Boolean(userToken)) return <something />;

// No need to give condition here
// If userToken is not false, this will return
return <main />;

Second, useEffect's dependency, according to what you wrote, which is二、useEffect的依赖,根据你写的,就是

  useEffect(() => {
    connectUser();
  });

It means you execute connectUser() everytime any component update.这意味着您每次更新任何组件时都执行connectUser() Pass a dependency.传递一个依赖。 If want no dependency, use [] , which means execute connectUser() only once when component mounts.如果不想依赖,请使用[] ,这意味着在组件挂载时只执行一次connectUser()

  useEffect(() => {
    connectUser();
  },[]);

Third, for Error: Objects are not valid as a React child (found: object with keys {username}) , if you get similar error in future, use console.log() to debug.第三,对于Error: Objects are not valid as a React child (found: object with keys {username}) ,如果以后遇到类似的错误,请使用console.log()调试。 In your case, console.log(userToken) and go see in console of your browser.在您的情况下, console.log(userToken)并在浏览器的控制台中查看。

Fourth, if you are handling about authentication, did you consider using firebase/auth ?第四,如果您正在处理身份验证,您是否考虑过使用firebase/auth

For useEffect running multiple times, please pass in a dependency array.对于 useEffect 多次运行,请传入一个依赖数组。 Check the react documentation on useEffect.检查 useEffect 上的反应文档。 You can start by giving an empty array as the second parameter to useEffect您可以首先将一个空数组作为 useEffect 的第二个参数

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

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