React Hook使用效应多个问题
这是我第一次使用使用效果挂钩。它的做法是阅读数据库,以查看值是否返回以及值返回的值,这是帐户标志的UserToken,因此它可以签名您。但是,我有2个问题。链接名称按钮并未自动签名,而必须在输入框中键入另一个字母才能登录。我尝试通过在第49行上的writeuserdata下添加ConnectUser来修复此操作,但这只是该站点崩溃了。我的第二个问题是,我无法在签名后的页面上显示{usertoken}。我收到错误:对象无效作为react子女(找到:带键{username}的对象)。如果您打算渲染一系列孩子,请改用阵列。
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>
);
}
This is my first time using a useEffect hook. 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. 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}). 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>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,请不要在时使用
。而是使用
使用。
其次,根据您所写的内容,USAUSEFECT的依赖性是
您每次执行
connectuser()
每次任何组件更新。通过依赖。如果不需要依赖关系,请使用[]
,这意味着执行connectuser()
仅在组件安装时一次。第三,对于
错误:对象无效作为React子女(找到:带键{username})
的对象,如果将来会遇到类似的错误,请使用console.log()调试。在您的情况下,
console.log(usertoken)
,然后在浏览器的控制台中查看。第四,如果您要处理身份验证,您是否考虑使用
firebase/auth
?First, please do not use
while
. Instead, useif
.Second, useEffect's dependency, according to what you wrote, which is
It means you execute
connectUser()
everytime any component update. Pass a dependency. If want no dependency, use[]
, which means executeconnectUser()
only once when component mounts.Third, for
Error: Objects are not valid as a React child (found: object with keys {username})
, if you get similar error in future, useconsole.log()
to debug. In your case,console.log(userToken)
and go see in console of your browser.Fourth, if you are handling about authentication, did you consider using
firebase/auth
?对于多次使用效果,请传递依赖项数组。检查有关使用效应的反应文档。您可以首先将空数组作为使用效果的第二个参数
For useEffect running multiple times, please pass in a dependency array. Check the react documentation on useEffect. You can start by giving an empty array as the second parameter to useEffect