等待thunk完成HTTP请求,然后再检查状态

时间:2020-06-29 20:32:36

标签: reactjs redux react-router-dom redux-thunk

我是使用thunk的React-Redux的一个新的学习阶段,所以我有一个login状态,其中有isLoggedIn个布尔值,我想检查是否希望用户重定向到主屏幕。

因此,我向Node.JS服务器发出了请求,该服务器返回了用户,并将isLoggedIn标志设置为true,但是当我针对它进行验证时,我需要单击两次Login按钮进行重定向。

我有99%的肯定是由于异步重击行为造成的,我的问题是如何解决?

const Login = ({ authenticate, IsUserLoggedIn }) => {
        const [email, setEmail] = useState('');
        const [password, setPassword] = useState('')
        const history = useHistory()
    
        const onSubmit = e => {
            e.preventDefault();
            const user = {
                email,
                password
            }
            authenticate(user); //<---- Thunk Request
            if (IsUserLoggedIn) {      //<---- Initially false, set to true on successful login
                history.push('/tracker')
            }
        }
        return (
            <>
                <h3>Login</h3>
                <form onSubmit={onSubmit}>
                    <div className="form-control">
                        <label htmlFor="email">Email</label>
                        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Enter email..." />
                    </div>
                    <div className="form-control">
                        <label htmlFor="Password">Password </label>
                        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Enter password..." />
                    </div>
                    <button className="btn">Login</button>
                </form>
            </>
        )
    }
    
    const mapStateToProps = state => ({
        IsUserLoggedIn: getIsUserLoggedIn(state)
    })
    
    const mapDispatchToProps = dispatch => ({
        authenticate: user => dispatch(getUser(user))
    })
    
    export default connect(mapStateToProps, mapDispatchToProps)(Login)

这是我的Thunk请求

export const getUser = user => async dispatch => {
    try {
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        }
        let body = JSON.stringify(user)
        const response = await axios.post('/api/v1/users/login',body, config)
        dispatch(setUserInfo(response))
    }
    catch (error) {
       dispatch(userError(error.response.data.error))
    }
}

这似乎是一个非常普遍的问题,但似乎找不到解决方法。让我知道是否需要更多代码

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

const Login = ({ authenticate, IsUserLoggedIn }) => {
  const history = useHistory();
  React.useEffect(() => {
    if (IsUserLoggedIn) {
      history.push('/tracker');
    }
  }, [IsUserLoggedIn, history]);

不确定useHistory是否每次都返回相同的对象,但我会这样想。