获取用户信息

841 阅读1分钟

1.getInitialState中方法fetchUserInfo()使用queryCurrentUser获取用户信息,且在initalState中公开了fetchUserInfo()方法,queryCurrentUser()默认获取的是mock数据,我们稍作修改即可实现获取用户信息效果。 image.png

2.找到queryCurrentUser方法所在位置 src/services/ant-design-pro/api.js中的方法currentUser image.png 代码如下:

export async function currentUser(options) {
  return request('/api/currentUser', {
    method: 'GET',
    ...(options || {}),
  });
}

3.若依后台中获取用户信息的接口方法如下图所示: image.png 修改currentUser方法请求接口地址为 /api/getInfo即可, method: 'GET'不变 这里注意一个问题就是若依后台接口/api/geInfo返回的用户信息在responsedata.user中,所以app.jsx中的fetchUserInfo方法中调用 const msg = await queryCurrentUser();后,要返回用户信息的话,返回的应该是msg.user;image.png 此处修改 return msg.data改为 return msg.user;

  1. src/pages/user/Login/index.jsx中的fetchUserInfo()方法不需要修改,因为其fetchUserInfo方法是调用了全局初始数据
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();

    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: userInfo }));
    }
  };

最近做了个小API应用,希望大家关注支持下: www.yuque.com/docs/share/…