我正在使用useContext來了解一個用戶是否已經登錄,如果是的話就存盤憑證。然而,當我改變組件時,該物件似乎被重置為默認值,使得它毫無用處。這個想法來自于https://stackoverflow.com/a/62362139,但它并不奏效。
UserContext.tsx
span class="hljs-keyword">import { createContext } from "react";
介面 UserManager {
username: string;
password: string;
setIsLoggedIn: Function。
}
const user: UserManager = {
username: ""。
password: "",
setIsLoggedIn: () => {}.
};
App.tsx
const App: React.FC = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false)。
const user = useContext(UserContext) 。
user.setIsLoggedIn = setIsLoggedIn;
return (
<UserContext.Provider value={user}> /span>
<IonApp>/span>
<IonReactRouter>/span>
<IonRouterOutlet>/span>
< Route exact path="/login" component={Login}/>
< Route exact path="/register" component={Register}/>
< Route exact path="/user_info" component={UserInfo}/>
< Route exact path="/main_tabs" component={MainTabs}/>
< 重定向 exact from="/" to={isLoggedIn ? "/main_tabs" : "/login" }/>
</IonRouterOutlet>
</IonReactRouter>/span>
</IonApp>/span>
</UserContext.Provider>
);
};
Login.tsx
const Login: React.FC = () => {
const user = useContext(UserContext)。
const [username, setUsername] = useState<string>("") 。
const [password, setPassword] = useState<string>("") 。
const login = (/span>) => {
if (username !==" && password !==") {
let body = {
username: 用戶名。
password: password
};
let request = sendRequest('POST'/span>, '/login'/span>, body);
request.onreadystatechange = () => {
if (request.ready ==4) {
let response = JSON.parse(request.response)。
if(response.success) {
user.username = username;
user.password = password;
user.setIsLoggedIn(true)。
window.location.href = "/main_tabs"; //user will reset after this page change.
} else if (! response.success) {
alert("Incorrect password") 。
}
}
};
} else {
alert("填寫兩個字")。
}
};
return (
<IonPage>/span>
<IonHeader>/span>
<IonToolbar>/span>
<IonTitle>/span>Concepimento</IonTitle>
</IonToolbar>/span>
</IonHeader>/span>
<IonContent fullscreen>/span>
< IonInput type="email" placeholder="Email" onIonChange={e => setUsername(e. detail.value!)}要求clearInput></IonInput>
< IonInput type="password"/span> placeholder="Password" onIonChange={e=> setPassword(e. detail.value!)}要求clearInput></IonInput>
<IonText onClick={() => window. location.href = "/main_tabs"}>密碼dimenticata?</IonText>
<br />< br /><br />
<IonButton onClick={login}>/span>
登錄
</IonButton> 登錄
<br />< br /><br />
<IonText>/span>
第一輪?
</IonText> Prima volta?
<br />/span>
<IonButton href="/register"/span>>
注冊
</IonButton>注冊。
</IonContent>/span>
</IonPage>/span>
);
};
我認為問題在于,當我匯入UserContext來訪問它的值時,用戶物件會被重新初始化(我放了一個列印陳述句,證實了這一點)。我四處尋找,但所有的資料都只談到了從子組件中訪問,從未修改過默認值。我怎樣才能做到這一點呢?
uj5u.com熱心網友回復:
window.location.href = "/main_tabs"/span>
你不應該在應用程式中使用location.href......
history.push("/main_tabs"/span>) 。
在你的函式中
const history = useHistory()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330243.html
標籤:
上一篇:簡單功能上的極端怪異行為
