這是我代碼的一部分。我在一個onClick按鈕中使用的login函式:
const {user, setUser} = useContext(UserContext)
const login = (/span>) => {
const errors = validateForm(field);
setErrors(errors)。
if (!errors.length) {
const username = fields.find((field) =>/span> field. id === 'username).input.state.value。
const password = fields.find((field) => field。 id == 'password').input.state.value;
setUser(用戶名)。
APIService.LoginUser({username, password})
}
}
它基本上是在validateForm(fields)中檢查用戶是否在表單中輸入了什么。如果那里沒有錯誤,那么它就將用戶變數設定為用戶輸入的任何用戶名。我希望這個用戶能夠被其他頁面使用,以便應用程式知道誰已經登錄。
這就是APIService.LoginUser()代碼:
。
export default class APIService {
static LoginUser(username, password) {
return fetch(`http://localhost:5000/userlookup`, {
'method': 'POST',
mode: 'cors',
headers: {
'Content-Type':'application/json'。
},
body: JSON.stringify(username, password)
})
.then(resp => window。 location.href = "file")
.catch(span class="hljs-params">error => console. log('error time! ', username, password))
}
我們的想法是,一旦用戶成功登錄,網站將直接進入 "個人資料 "頁面。在個人資料頁面上,我有一個簡單的問候語:
const Profile = (/span>) => {
const {user, setUser} = useContext(UserContext) 。
return (
<IonPage>
<IonContent>/span>
<h1>
你好,{用戶}。
</h1> 你好,{user}。
</IonContent>/span>
</IonPage>/span>
)
};
export default Profile;
(從標簽中,你可以看到這是一個ionic應用程式,但我認為這無關緊要)
我的問題是,當我嘗試使用上述代碼登錄時,在我被重定向到profile頁面后,問候語并沒有更新為登錄的用戶的用戶名。然而,當我注釋掉LoginUser函式的這一部分時:
.then(resp =>/span> window. location.href = "file")
.catch(span class="hljs-params">error => console. log('error time!', username, password)
并手動導航到profile頁面,它正常作業! 它問候了登錄的用戶! 這是一個異步的問題嗎?我的理論是,當它自動重定向到profile頁面時,它做得太快了,UseContext無法告訴它該怎么做?這個理論是真的嗎?是其他原因嗎?我怎樣才能解決這個問題呢?
謝謝你
uj5u.com熱心網友回復:
window.location.href = "file"
這不是Ionic Framework中導航到不同頁面的正確方法
const history = useHistory()
然后轉到另一條路線
history.push("/profile"/span>)
參見檔案 - https://ionicframework.com/docs/react/navigation#ionreactrouter
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/318056.html
標籤:
上一篇:子組件沒有收到傳遞的道具
