登录后和异步调用后重新呈现

时间:2018-05-30 00:03:42

标签: javascript reactjs asynchronous axios

在我的Login反应组件中,我在handleLogin方法中调用handleSubmit。然后......(见下文)......

import React from "react"
import { Redirect } from "react-router-dom"
import axios from 'axios'
import Form from "./Form"
import View from "./View"
import { handleLogin, isLoggedIn } from "../utils/auth"

export default class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: ``,
      password: ``,
    };
  }

  handleUpdate(event) {
    this.setState({
      [event.target.name]: event.target.value,
    })
  }

  handleSubmit(event) {
    event.preventDefault()
    handleLogin(this.state)
  }

  render() {
    if (isLoggedIn()) {
      return <Redirect to={{ pathname: `/app/profile` }} />
    }

    return (
      <View title="Log In">
        <Form
          handleUpdate={e => this.handleUpdate(e)}
          handleSubmit={e => this.handleSubmit(e)}
        />
      </View>
    )
  }
}

...在handleLogin方法(从下面../utils/auth导入)中,我进行异步调用(axios.post):

// in /utils/auth.js

import axios from 'axios'

const isBrowser = typeof window !== `undefined`

const getUser = () =>
  window.localStorage.gatsbyUser
    ? JSON.parse(window.localStorage.gatsbyUser)
    : {}

const setUser = user => (window.localStorage.gatsbyUser = 
JSON.stringify(user))

export const handleLogin = ({ email, password }) => {
  if (!isBrowser) return false

  axios.post(`${process.env.API_URL}/sessions`, {
    email: email,
    password: password,
  })
  .then(response => {
    console.log(response);
    return setUser({
      name: `Jim`,
      legalName: `James K. User`,
      email: email,
    })
  })
  .catch(error => {
    return false
  });
}

export const isLoggedIn = () => {
  if (!isBrowser) return false

  const user = getUser()
  return !!user.email
}

我遇到的问题是在render()解析之前调用axios.post / handleLogin(this.state)方法,从而阻止render()方法将isLoggedIn()看作返回{{ 1}}。

我想知道如何阻止在true解决之前调用render()方法。

1 个答案:

答案 0 :(得分:2)

您可以通过触发重新渲染来解决此问题。根据您的代码示例,我认为您只需等待handleLogin异步调用完成,然后检查用户是否已记录isUserLogin,您应该添加镜像的本地状态{ {1}}触发重新渲染。

以下是使用Promise的示例,您可以使用async / await实现相同的功能:

isUserLogin