【问题标题】:The code in the then method is not executed and error handling is performedthen方法中的代码不执行,进行错误处理
【发布时间】:2020-11-09 03:17:47
【问题描述】:

我正在使用 React 和 firebase 开发一个网络应用程序,但我无法让它工作。

这是我的代码

import React, { useRef, useState } from "react"
import { Form, Button, Card, Alert } from "react-bootstrap"
import { useAuth } from "../contexts/AuthContext"
import { Link, useHistory, Redirect, Route } from "react-router-dom"
import { db } from "../firebase"
import Dashboard from "../components/Dashboard"

export default function UpdateProfile() {
  const usernameRef = useRef()
  const emailRef = useRef()
  const passwordRef = useRef()
  const passwordConfirmRef = useRef()
  const { updateUser, currentUser, updatePassword } = useAuth()
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const history = useHistory()

  function handleSubmit(e) {
    e.preventDefault()
    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
      return setError("Passwords do not match")
    }

    if (passwordRef.current.value) {
      updatePassword(passwordRef.current.value)
    }

    const uid = currentUser.uid
    db.collection('users').doc(uid).get()
    .then(snapshot => {
      const data = snapshot.data() 
      try {
        setLoading(true)
        setError("")
        updateUser(usernameRef.current.value, emailRef.current.value, data)
        history.push('/dashboard')
      } catch {
        setError("Failed to update account")
      }
      setLoading(false)
    })
  }

  return (
    <>
      <Card>
        <Card.Body>
          <h2 className="text-center mb-4">Update Profile</h2>
          {error && <Alert variant="danger">{error}</Alert>}
          <Form onSubmit={handleSubmit}>
            <Form.Group id="username">
              <Form.Label>Name</Form.Label>
              <Form.Control
                type="text"
                ref={usernameRef}
                required
                defaultValue={currentUser.username}
              />
            </Form.Group>
            <Form.Group id="email">
              <Form.Label>Email</Form.Label>
              <Form.Control
                type="email"
                ref={emailRef}
                required
                defaultValue={currentUser.email}
              />
            </Form.Group>
            <Form.Group id="password">
              <Form.Label>Password</Form.Label>
              <Form.Control
                type="password"
                ref={passwordRef}
                placeholder="Leave blank to keep the same"
              />
            </Form.Group>
            <Form.Group id="password-confirm">
              <Form.Label>Password Confirmation</Form.Label>
              <Form.Control
                type="password"
                ref={passwordConfirmRef}
                placeholder="Leave blank to keep the same"
              />
            </Form.Group>
            <Button disabled={loading} className="w-100" type="submit">
              Update
            </Button>
          </Form>
        </Card.Body>
      </Card>
      <div className="w-100 text-center mt-2">
        <Link to="/">Cancel</Link>
      </div>
    </>
  )
}

这是用户编辑功能的代码:在表单中输入一个值,然后按下按钮运行handleSubmit。

  function updateUser(username, email, data) {
    const uid = data.uid
    db.collection('users').doc(uid).set({
      email: email,
      username: username,
    }, {merge: true})
  }

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(async(user) => {
      if (user) {
        const uid = user.uid
        console.log(uid)
        await db.collection('users').doc(uid).get()
          .then(snapshot => {
            const data = snapshot.data()
            setCurrentUser(data)
            setLoading(false)
          })
      }
    })
    
    return unsubscribe
  }, [])

下面的代码重写了firestore数据在这个updateUser函数执行后,我们想在handleSubmit的then中做一个history.push来重定向到/dashboard,但是我们想让控制台说“成功!”控制台和“失败!在控制台和消息“成功!”出现在应用程序上。

当我查看 firestore 数据时,我发现我输入的值已正确反映在 firestore 中。

这告诉我handleSubmit 的then 部分不起作用,但我不知道为什么它不起作用。

如果您有解决方案,我很乐意听到。 谢谢。

【问题讨论】:

    标签: javascript reactjs firebase asynchronous google-cloud-firestore


    【解决方案1】:

    你需要

    • await 或将.catch 放到updateUser Promise 链上(try/catch 只有在 Promise 为 awaited 时才会捕获异步错误)
    • updateUser返回承诺
    • 函数 传递给 .then 回调 - 您的 .then(console.log("success!!")) 调用 console.log 立即 并将 undefined 传递给 .then
    function handleSubmit(e) {
        e.preventDefault()
        if (passwordRef.current.value !== passwordConfirmRef.current.value) {
            return setError("Passwords do not match")
        }
    
        if (passwordRef.current.value) {
            updatePassword(passwordRef.current.value)
        }
    
        const uid = currentUser.uid
        db.collection('users').doc(uid).get()
            .then(snapshot => {
                const data = snapshot.data()
                setLoading(true)
                setError("")
                return updateUser(usernameRef.current.value, emailRef.current.value, data);
            })
            .then(() => {
                // Success
                history.push('/dashboard')
            })
            .catch((error) => {
                setError("failed!!")
            })
            .finally(() => {
                setLoading(false)
            });
    }
    
    function updateUser(username, email, data) {
        const uid = data.uid
        return db.collection('users').doc(uid).set({
            email: email,
            username: username,
        }, { merge: true })
            .then(() => console.log("success!!"))
    }
    

    【讨论】:

    • 谢谢!有效。但是,重定向到 /dashboard 后,我想反映我输入的值,但它反映的是我输入之前的值。重定向到 /dashboard 后如何使值反映?
    • want to reflect the value I entered 是什么意思?您是否在某处或某处记录了值?
    • 抱歉没有解释。我添加了一些代码。这个handleSubmit 函数用于编辑用户信息的组件。当您在表单中输入值并单击提交按钮时,handleSubmit 函数输入的值将传递给 updateUser 函数,该函数随后会在 useEffect 中引用 firebase 集合中的数据并将其显示在应用程序上。但是表单中输入的值会反映在firestore中,但是被重定向后,在编辑之前显示的是用户的信息。
    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2022-11-14
    • 2019-07-15
    • 2019-10-08
    相关资源
    最近更新 更多