gpt4 book ai didi

javascript - 修复 "Can' t perform a React state update on an unmounted component”错误

转载 作者:行者123 更新时间:2023-11-30 13:59:28 28 4
gpt4 key购买 nike

当我尝试在我的网络应用程序中推送到一个新页面时,下面的代码给出了一个控制台错误:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in PasswordResetPage (created by Context.Consumer)

您会在注释掉的代码中注意到我尝试使用 useEffect 因为这是大多数 stackoverflow 答案所指向的。但是,错误仍然存​​在。如何在此上下文中使用 history.push 并消除错误?

import React, { useState /* , useEffect */ } from 'react'
import useForm from 'react-hook-form'
import Logo from '../assets/images/logo-icon-orange.png'
import TextInput from '../components/TextInput'
import Footer from '../components/Footer'
import AnimatedButton from '../components/AnimatedButton'
import logger from '../logger'
import { sleep } from '../utils/promise'
import PasswordResetSchema from './validation/PasswordResetSchema'

const PasswordResetPage = ({ history }) => {
const [isSubmitting, setSubmitting] = useState(false)
// const [isDone, setDone] = useState(false)
const { register, handleSubmit, errors } = useForm({
validationSchema: PasswordResetSchema,
})

const onSubmit = async data => {
setSubmitting(true)
await sleep(2000)
logger.info('form data', data)
// setDone(true)
history.push('/confirmation')
}

// useEffect(() => {
// if (isDone) {
// history.push('/confirmation')
// }
// })


return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<div className="text-center mb-4">
<img className="mb-4" src={Logo} alt="Striver" width={72} />
<h1 className="h3 mb-3 font-weight-normal">Password reset</h1>
<p>Enter your email address below and we will send you instructions on how you can reset your password.</p>
</div>

<div className="form-label-group">
<TextInput type="email" id="email" register={register} label="Email address" errors={errors} />
</div>

<AnimatedButton actionTitle="Next" isSubmitting={isSubmitting} />
<Footer />
</form>
)
}

export default PasswordResetPage

最佳答案

看看这是否适合你:

使用工作示例编写沙盒代码:

https://codesandbox.io/s/reactrouteranswerso-817bp

const onSubmit = async data => {
setSubmitting(true)
await sleep(2000)
logger.info('form data', data)
setDone(true)
}

useEffect(() => {
if (isDone) {
history.push('/confirmation')
}
},[isDone]);

CodeSandbox 上的工作代码:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import "./styles.css";

function App() {
const [user, setUser] = useState(null);

function doLogin() {
console.log("Inside do login...");
setUser("someUserID");
}

function doLogout() {
console.log("Inside do logout...");
setUser(null);
}

return (
<Router>
<AllRoutes user={user} doLogin={doLogin} doLogout={doLogout} />
</Router>
);
}

function AllRoutes(props) {
console.log("Rendergin AllRoutes...");
// console.log(props);
return (
<Switch>
<Route exact path="/" component={Component1} />
<Route exact path="/comp2" component={Component2} />
</Switch>
);
}

function Component1(props) {
const [isDone, setIsDone] = useState(false);

useEffect(() => {
if (isDone) {
props.history.push("/comp2");
}
}, [isDone, props.history]);

return (
<React.Fragment>
<div>Component1</div>
<button onClick={() => setIsDone(true)}>Submit</button>
</React.Fragment>
);
}

function Component2(props) {
const [goBack, setGoBack] = useState(false);

useEffect(() => {
if (goBack) {
props.history.push("/");
}
}, [goBack, props.history]);

return (
<React.Fragment>
<div>Component2</div>
<button onClick={() => setGoBack(true)}>Go Back</button>
</React.Fragment>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关于javascript - 修复 "Can' t perform a React state update on an unmounted component”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608065/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com