【发布时间】:2020-03-06 04:49:48
【问题描述】:
我遇到了一个似乎是由于异步调用引起的问题。我有一个进行 API 调用并推送到仪表板页面的操作。该 API 调用还会根据它返回的响应更新 state.account.id:
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials);
props.history.push('/protected');
e.target.reset();
}
loginAndGetAccount 来自此操作:
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
在仪表板页面上,我已将 useEffect 设置为根据 state.account.id 中保存的值动态进行另一个 API 调用。但是,似乎第一个 API 调用在响应返回并更新 state.account.id 之前推送到仪表板页面。因此,当在那里进行第二次 API 调用时,它会将 state.account.id 作为未定义传递给该动态 API 调用,这当然会导致调用失败。我该如何解决这个问题?
以下是正在发生的事情:
const Dashboard = props => {
const [accountInfo, setAccountInfo] = useState({});
useEffect(() => {
console.log(props.accountId);
axiosWithAuth()
.get(`/operator/${props.accountId}`)
.then(res => {
console.log(res);
})
.catch(err => console.log(err));
}, [])
return (
<div>
<h1>This is the Dashboard component</h1>
</div>
)
}
const mapStateToProps = state => {
return {
accountId: state.account.id
}
}
export default connect(mapStateToProps, {})(Dashboard);
【问题讨论】:
标签: reactjs redux axios race-condition use-effect