Axios.All(将多个请求链接在一起)不起作用?

时间:2019-07-17 21:59:32

标签: javascript reactjs axios

编辑:我解决了。问题是我将userData对象传递给了其他不需要全部的对象。当我缩小范围时,我得到了希望达到的目标。

因此,我试图做到这一点,以便当用户在我的Web应用程序上注册时,它将自动将其登录,然后重定向到主页。重定向到主页有效,但未注册用户或设置用户详细信息。我看了一下文档并认为我做得正确,但是仍然没有结果?

authActions.js文件:

// Register User
export const registerUser = (userData, history) => dispatch => {
    axios.post('/users/register', userData)
        //.then(res => history.push('/login'))
        .catch(err => 
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data
            })    
        );
}

// Login - Get User Token
export const loginUser = (userData) => dispatch => {
    axios.post('/users/login', userData)
        .then(res => {
            // Save to localStorage
            const { token } = res.data;
            // Set token to LocalStorage
            localStorage.setItem('jwtToken', token);
            // Set token to Auth header
            setAuthToken(token);
            // Decode token to get user data
            const decoded = jwt_decode(token);
            // Set current user
            dispatch(setCurrentUser(decoded));
        })
        .catch(err => 
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data
            }) 
        );
}

// Set logged in user
export const setCurrentUser = (decoded) => {
    return {
        type: SET_CURRENT_USER,
        payload: decoded
    }
} 



// Register, Login, Set User all at the same time
export const regLogSetUser = (userData, history) => dispatch => {
    axios.all([registerUser(), loginUser(), setCurrentUser()])
    .then(res => history.push('/'))
    .catch(err => 
        dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        })    
    );
}

在我的Register组件中,我还正确地调用了Prop Function(在底部)(在顶部将其导入之后)。

Register.propTypes = {
    regLogSetUser: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired
}


const mapStateToProps = (state) => ({
    auth: state.auth,
    errors: state.errors
});

export default connect(mapStateToProps, { regLogSetUser })(withRouter(Register));

以下是文档的链接:

https://github.com/axios/axios

这就是Axios.all()的意思

Performing multiple concurrent requests

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

感谢您的帮助。还在学习!

0 个答案:

没有答案