reactjs 如何访问同一文件中另一个导出函数中的导出函数?

w8f9ii69  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(106)

我试图从loadUser函数中获取login函数中的用户数据。但是它拒绝运行,我不确定这里出了什么问题?
我想你可以在同一个文件中调用一个导出的函数?

// Login User
export const login = (formData) => async dispatch => {
  const config = {
    heraders: {
      'Content-Type': 'application/json'
    }
  }
  try {
    const res = await axios.post('/api/auth', formData, config);
    dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data
    });
    console.log('Calling load user here?');
    loadUser();
    console.log('loadUser did not run?');
  } catch (err) {
    dispatch({
      type: LOGIN_FAIL,
      payload: err.response.data.msg
    });
  }
}

// Load User
export const loadUser = () => async dispatch => {
  console.log('Is this running');
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }
  console.log('GETTING USER');
  try {
    const res = await axios.get('/api/auth');
    dispatch({ 
      type: USER_LOADED,
      payload: res.data
    });
  } catch (err) {
    dispatch({ 
      type: AUTH_ERROR
    });
  }
}

我希望loadUser函数运行,但它没有运行。

x0fgdtte

x0fgdtte1#

您应该能够像调用任何其他JavaScript函数一样,在login函数中通过名称调用loadUser函数。
下面介绍如何更新login函数以调用loadUser函数:

// Login User
export const login = (formData) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  }
  try {
    const res = await axios.post('/api/auth', formData, config);
    dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data
    });
    console.log('Calling load user here?');

    // Call the loadUser function, passing in dispatch as an argument
    loadUser()(dispatch);

    console.log('loadUser did not run?');
  } catch (err) {
    dispatch({
      type: LOGIN_FAIL,
      payload: err.response.data.msg
    });
  }
}

由于loadUser函数是一个async函数,它接受dispatch作为参数,因此需要如下调用它:loadUser()(dispatch) .

相关问题