[英]useState not updating properly with axios and Promise
我有這個代碼:
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const onSubmitHandler = (event) => {
event.preventDefault();
setLoading(true);
axios({
method: 'post',
url: `${process.env.REACT_APP_API_URL}users/auth/sign_in`,
data: { email, password },
headers: { 'content-type': 'application/json' },
})
.then(function (response) {
setSuccess(true);
console.log(response, ' sucesso');
const authData = {
accessToken: response.headers['access-token'],
client: response.headers.client,
uid: response.headers.uid,
};
localStorage.setItem('authData', JSON.stringify(authData));
})
.catch(function (error) {
setLoading(false);
setError(true);
console.log(error, 'error');
});
};
if(success) return <Redirect to="/" />
它是一個登錄頁面,當用戶按下登錄按鈕時,這個函數就會被執行。 它工作得很好,但我在重定向到主頁時遇到了一些麻煩。
我添加了一個success
常量作為useState
並且每次請求成功時,它應該使用setSuccess(true)
將success
設置為 true 並將用戶重定向到/
使用react-router-dom
但它不起作用。 狀態仍為假。 我做錯了什么?
我也試過像這樣使用useEffect
:
const returnFunc = () => <Redirect to="/" />;
useEffect(() => {
if (success) {
returnFunc();
}
}, [success, loading]);
我認為你應該這樣做:
useEffect(() => {}, [success, loading]);
if(success) return <Redirect to="/" />
如果您在 UseState 中調用 returnFunc() 它將不起作用,只是 UseEffect 內沒有任何內容,但只有 [success] 會重新渲染頁面,因為您將成功設置為 true,然后它應該帶您到主頁。
你能試試這個嗎
return success ? <Redirect to="/" /> : "Render somthing for none login state";
...
import { BrowserRouter as Router } from "react-router-dom";
...
return (
...
<Router>
{success && <Redirect to="/" />}
</Router>
)
// or you can try this way
import { useHistory } from "react-router-dom";
let history = useHistory();
...
useEffect(() => {
if (success) {
setSuccess(false)
history.push('/');
}
}, [success]);
固定添加window.location.href = '/';
到.then
並添加了一個 if 來檢查是否有 localStorage。
if (localStorage.getItem('authData')) {
return <Redirect to="/" />;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.