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



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

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

我 99% 确定这是因为异步 thunk 行为,我的问题是如何解决它?

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))
}
}

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

您可以尝试以下操作:

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

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

相关内容

最新更新