代码之家  ›  专栏  ›  技术社区  ›  Aldo

安装仪表板后,authProvider正在完成其承诺

  •  1
  • Aldo  · 技术社区  · 7 年前

    使用[react admin]

    我有一个customDashboard,它验证一个参数并重定向到名为 pages

    class DashBoard extends Component {
        componentDidMount() {
        const { push } = this.props;
        if (!localStorage.getItem("activePage")) {
            push("/pages");
        }
        ...
    

    我还有一个从后端获取身份验证数据的authProvider:

    export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const { authResponse } = params;
        const request = new Request('https://localhost:8080/users/auth', {
            method: 'POST',
            body: JSON.stringify({ userID }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });
        fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.body);
                 }
                 return response.json();
            }).then(({ user }) => {
                  localStorage.setItem('token', user.token);
                  localStorage.setItem('name', user.name);
                  localStorage.setItem('email', user.email);
                  localStorage.setItem('activePage', user.activePage);
            }).catch((err) => {
                  return Promise.reject(err);
            }).finally(() => {
                  return Promise.resolve();});
            ...
    

    我精简了代码,只显示了承诺部分。

    finally ,正在之后执行 “/pages” 就像我在console.log中看到的那样。而且,在 我检查了由后端返回的activePage,发生了什么太晚了。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Matt Carlotta    7 年前

    尝试使用 async/await ,更容易遵循流程:

    export default async (type, userID) => {
      if (type === AUTH_LOGIN) {
        try  {
          const res =  await fetch('https://localhost:8080/users/auth', {
            method: 'POST',
            body: JSON.stringify({ userID })
            headers: new Headers({ 'Content-Type': 'application/json' }),
          }) // fetch API data
    
          const { user: { token, name, email, activePage } } = await res.json(); // convert to JSON, from the JSON's user prop, pull out token, name, email, activePage
    
          localStorage.setItem('token', token);
          localStorage.setItem('name', name);
          localStorage.setItem('email', email);
          localStorage.setItem('activePage', activePage);
    
        } catch(err) { console.error(err); }
      }
    }
    
        2
  •  0
  •   Aldo    7 年前

    我到处找我发现了这个 answer 对我的代码做了一些修改。现在工作正常:

    • async ,调用 auth 函数并在最后返回一个承诺。

      // in src/authProvider.js
      export default async (type, params) => {
          if (type === AUTH_LOGIN) {    
              const { authResponse } = params;
              const user = await auth(userID);
              localStorage.setItem('token', user.token);
              if (user.activePage) localStorage.setItem('activePage', user.activePage);
      
              return Promise.resolve();
      
    • 认证 函数返回一个承诺:

      const auth = async (userID) => {
        const request = new Request('https://localhost:8080/users/auth', {
          method: 'POST',
          body: JSON.stringify({ userID }),
          headers: new Headers({ 'Content-Type': 'application/json' }),
        });
      
        return fetch(request)
          .then(response => {
            if (response.status < 200 || response.status >= 300) {
              throw new Error(response.body);
            }
            return response.json();
          })
          .then(({ user }) => {
            return user;
          });
      }