慕妹3146593
2021-08-20 17:25:56
我正在構建一個使用 React、Express、Sequalize 和 mySQL 的全棧網站。到目前為止,它具有注冊和登錄等功能,但是當我嘗試添加錯誤處理時,它失敗了。我收到以下錯誤消息:Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead. in div (at Login.js:46) in form (at Login.js:44) in div (at Login.js:43) in div (at Login.js:42) in div (at Login.js:41) in Login (created by Route) in Route (at App.js:26) in Switch (at App.js:23) in div (at App.js:22) in div (at App.js:15) in Router (created by BrowserRouter) in BrowserRouter (at App.js:14) in App (at src/index.js:7)當我添加此代碼{this.state.errenter code hereors}以顯示諸如“找不到用戶”之類的錯誤消息時。import React, { Component } from "react";import { login } from "./UserFunctions";class Login extends Component { constructor() { super(); this.state = { email: "", password: "", errors: {} }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } onSubmit(e) { e.preventDefault(); const user = { email: this.state.email, password: this.state.password }; login(user, (res, err) => { if (res) { this.props.history.push(`/`); } else { this.setState({ errors: err }); } }); } render() { return ( <div className="container"> <div className="row"> <div className="col-md-6 mt-5 mx-auto"> <form noValidate onSubmit={this.onSubmit}> <h1 className="h3 mb-3 font-weight-normal">Please sign in</h1> <div className="alert alert-danger" role="alert"> {this.state.errors} </div> <div className="form-group"> <label htmlFor="email">Email address</label> <input type="email" className="form-control" ); }}export default Login;感謝有關如何解決此問題的任何指導。
2 回答

慕哥6287543
TA貢獻1831條經驗 獲得超10個贊
為什么會出現此錯誤?
因為您在執行{this.state.errors}.
如何解決?
首先,您需要提供login函數正在做什么以及是什么err。
您可能只想獲取錯誤字符串,但它err是一個對象。
正如您在錯誤消息中看到的那樣
對象作為 React 子對象無效(找到:帶有鍵 {} 的對象)
這意味著這err是一個空對象。這可以在你聲明它的狀態中看到
this.state = {
email: "",
password: "",
errors: {} // declaring it as an object
};
您應該將錯誤聲明為字符串
this.state = {
email: "",
password: "",
errors: "" // declaring it as a string
};
或者,這取決于是什么err的的login功能,它應該包含一些字符串來呈現。

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
該err
對象很可能是 的一個實例,Error
如果是這種情況,它將包含一個message
屬性。
所以,這應該是你想要顯示的 { this.state.errors.message }
添加回答
舉報
0/150
提交
取消