简体   繁体   English

useState 没有使用 axios 和 Promise 正确更新

[英]useState not updating properly with axios and Promise

I have this code:我有这个代码:

  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="/" />

It is a login page and this function gets executed when the user press the Login button.它是一个登录页面,当用户按下登录按钮时,这个函数就会被执行。 It works just fine but I'm having some trouble to make it redirect to the main page.它工作得很好,但我在重定向到主页时遇到了一些麻烦。

I have added a success const as useState and everytime the request is successful, it was supposed to set success to true with setSuccess(true) and redirect the user to / using react-router-dom but it is not working.我添加了一个success常量作为useState并且每次请求成功时,它应该使用setSuccess(true)success设置为 true 并将用户重定向到/使用react-router-dom但它不起作用。 The state still as false.状态仍为假。 What I'm doing wrong?我做错了什么?

I have also tried using useEffect like this:我也试过像这样使用useEffect

  const returnFunc = () => <Redirect to="/" />;
  useEffect(() => {
    if (success) {
      returnFunc();
    }
  }, [success, loading]);

I think you should just do:我认为你应该这样做:

useEffect(() => {}, [success, loading]);

if(success) return <Redirect to="/" />

If you are calling your returnFunc() in the UseState it is not going to work, just with nothing inside the UseEffect but only [success] is going to re-render the page because you set success to true and then it should take you to the main page.如果您在 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]);

Fixed adding window.location.href = '/';固定添加window.location.href = '/'; to the .then and added an if to check if there is localStorage..then并添加了一个 if 来检查是否有 localStorage。

  if (localStorage.getItem('authData')) {
    return <Redirect to="/" />;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM