我對 React 和 Redux 相當陌生,并且在根據服務器的錯誤響應(使用 Express)顯示錯誤狀態時遇到了一些困難。我研究過的大多數其他類似問題都與 onClick、onSubmit 或 onChange 相關,但我還沒有看到像我這樣的問題。預期結果:從存儲中檢索錯誤狀態并顯示在組件內問題源于此部分:if (nextProps.errors){ this.setState({ errors: nextProps.errors }); }完整的Login.js:import React, { Component } from "react";import { connect } from "react-redux";import PropTypes from "prop-types";import "../css/login.css";import { loginUser } from "../../redux/actions/authActions";import TextFieldGroup from "../common/textFieldGroup";class Login extends Component { constructor() { super(); this.state = { username: '', password: '', errors: {} }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { if (this.props.auth.isAuthenticated) { this.props.history.push('/dashboard'); } } componentDidUpdate(nextProps) { if (nextProps.auth.isAuthenticated) { this.props.history.push('/dashboard'); } if (nextProps.errors){ this.setState({ errors: nextProps.errors }); } } onSubmit(e) { e.preventDefault(); const userData = { username: this.state.username, password: this.state.password }; this.props.loginUser(userData); } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } render() { const { errors } = this.state; return ( <div className="login"> <div className="container"> <div className="row"> <div className="col-md-8 m-auto"> <h1 className="display-4 text-center">Log In</h1> <p className="lead text-center"> <input type="submit" className="btn btn-info btn-block mt-4" /> </form> </div> </div> </div> </div> ); }}我試過了:將值分配給臨時變量,但這非常笨拙,并且在我看來使代碼變得混亂。驗證它是否為空/不為空,這自然會加強無限循環或積極驗證,因為它不為空,因此錯誤狀態永遠不會在頁面上更新。我確實從服務器獲得了正確的錯誤響應,正如我在 Redux 開發工具中看到的那樣。提前致謝。
來自 Redux 的 React 狀態更新導致超出最大更新深度錯誤
互換的青春
2023-12-14 15:48:07