[英]How can I store user information in Next.JS + Rails API backend?
我是 Next.js 和 React 的新手,我曾經用 Rails 開發整個應用程序。
我想將 rails API 與 Next.js 結合起來。 我的 JWT 后端有一個端點,當在標頭中使用 JWT 令牌請求時,該端點返回包含用戶信息的 JSON 對象。 在我的_app.js
,我試圖通過使用useState
和useEffect
來驗證使用useState
useEffect
如下所示:
export default function MyApp(props) {
const [user, setUser] = useState({})
useEffect(function () {
const token = localStorage.getItem('token')
if (token) {
fetch('http://localhost:3001/auto_login', {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((resp) => resp.json())
.then((data) => {
console.log(data) // {id: 1, email: "test@example.com"}
setUser(data)
console.log(user) // {}
})
}
}, [])
return (
<>
{ // some code }
</>
)
}
在我的第一個console.log
,它返回一個我想存儲在user
。 但是,在我希望返回相同結果的第二個console.log
中,我得到了一個空對象。
我是否遺漏了任何東西,或者有什么我必須整體考慮的要點? 我已經嘗試使用async/await
實現它,但這似乎並沒有解決我的問題。
這是因為該效果不知道依賴對象的狀態變化。
如果你這樣做(見下面的代碼),你會看到user
被登錄。 例如,在第一個效果的第一次運行的上下文中,即使您正在設置user
狀態,在效果內部它也不知道新值。
順序是這樣的。
[]
初始狀態運行(這實際上意味着運行一次,並使用當前狀態, user => {}
)[]
=> console.log(data)
[]
=> setUser(data)
[]
=> console.log(user)
// 當前{}
看這里的useEffect解釋
export default function MyApp(props) {
const [user, setUser] = useState({ email: null, id: null })
// same useEffect / modify your existing code
// you could add user in here .but then the api call will fire again,
// thus an infinite loop could happen, so you would need to wrap
// the call in an if to check to prevent that, see my alterations
useEffect(function () {
const token = localStorage.getItem('token')
if (token && !user.id) {
fetch('http://localhost:3001/auto_login', {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((resp) => resp.json())
.then((data) => {
console.log(data) // {id: 1, email: "test@example.com"}
setUser(data)
console.log(user);
})
}
}, [user]); // [] => changed to => [user]
// new / additional useEffect
// alternatively this effect will trigger when
// this objects state changes (and you wont need the checks as per above)
useEffect(() => {
console.log(user);
}, [user]);
return (
<>
{ // some code, e.g if you referenced user here, example. user.email, it would work. }
{ // Would probably initially be empty, when when the ajax call completes the value would/could be set }
</>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.