[英]React Can't perform a React state update on an unmounted component error
[英]Resolve "Can't perform a React state update on an unmounted component" Error
我有一個關於如何修復“無法執行 React state 更新”錯誤消息的問題。 我確實進一步了解了這個問題,並表示這只是一個警告。 請注意,我是 React 的初學者。 這是問題如下。 我有一個 header 組件,它由一個導航欄組成,該導航欄具有兩種狀態,用於切換移動導航菜單按鈕,另一種狀態用於更改滾動時的背景顏色。 我實現了導航欄切換功能,並開始在 JS 控制台中收到所謂的錯誤。 經過進一步檢查,我確定這與我的切換開關 state 有關。我們將不勝感激。 提前致謝!
import React, { useState } from 'react';
import { Icon } from 'react-icons-kit';
import {bars} from 'react-icons-kit/fa/bars';
import {times} from 'react-icons-kit/fa/times';
import {chevronCircleDown} from 'react-icons-kit/fa/chevronCircleDown';
const Header = (props) => {
const [toggle, setToggle] = useState(false);
const [navbar, setNavbar] = useState(false);
const handleToggle = () => {
setToggle(!toggle);
}
const changeBackground = () => {
if(window.scrollY >= 60) {
setNavbar(true);
}
else {
setNavbar(false);
}
}
window.addEventListener('scroll', changeBackground);
if(props.data){
var description = props.data.description;
var navigation = props.data.navigation.map(item => {
return <li key={item.linkname} className="nav-item"><a href={item.href} className={item.className}>{item.linkname}</a></li>
});
}
return (
<header id="home" className="main-header">
<div className="container">
<nav className={navbar ? 'navbar nav-bg' : 'navbar'} aria-label="Main Navigation" id="navbar">
<ul className={toggle ? 'navbar-nav active' : 'navbar-nav'} id="nav">
{navigation}
</ul>
<button className="btn-mobile-nav" type="button" aria-controls="nav" aria-expanded={toggle ? 'true' : 'false'} aria-label="Mobile Navigation button" title="Mobile menu button" onClick={handleToggle}>{toggle ? <Icon icon={times} size={24} title="Close Menu"/> : <Icon icon={bars} size={24} title="Open Menu"/> }</button>
</nav>
</div>
<div className="header-content d-flex flex-column">
<div>
<h1 className="header-title"><span className="typed"></span></h1>
<p className="header-summary">{description}</p>
</div>
</div>
<a href="#about" id="to-about" className="btn-up-down" title="Go to About" aria-label="Go to About section"> <Icon icon={chevronCircleDown} size={54}/></a>
</header>
);
}
export default Header;
import React from 'react'; import SkipNav from './Components/SkipNav'; import Header from './Components/Header'; import Footer from './Components/Footer'; import About from './Components/About'; import Resume from './Components/Resume'; import Portfolio from './Components/Portfolio'; import Contact from './Components/Contact'; class App extends React.Component { constructor(props){ super(props); this.state = { resumeData: [], recipName: '', recipEmail: '', recipSubject: '', recipMessage: '' }; this.handleChange = this.handleChange.bind(this); this.handleCaptchaChange = this.handleCaptchaChange.bind(this); this.handleEmailSent = this.handleEmailSent.bind(this); } getResumeData = () => { fetch('/data.json').then(response => { return response.json() }).then(data => { this.setState({ resumeData: data }); }).catch(error => { console.log(error) alert(`Unable to retrieve data. See JS console for details: Error.${error}`) }) } handleChange = (event) => { this.setState({ [event.target:name]. event.target;value }). } handleCaptchaChange = (value) => { console:log("Captcha value,"; value). } handleEmailSent = (event) => { event;preventDefault(). if (this.state.recipName === '' || this.state.recipEmail === '' || this.state.recipSubject === '' || this.state.recipMessage === '') { console;log('All fields required;') alert('All fields are required:'). return. } let data = { recipName, this:state.recipName. recipEmail, this:state.recipEmail. recipSubject, this:state.recipSubject. recipMessage; this.state;recipMessage }: console.log(data). fetch (`https,//api:eahassan,me/sendEmail`: { method: 'POST', headers: {'Content-Type'. 'application/json'}. body. JSON.stringify(data) });then((response) => { console;log(response.data). alert("E-Mail sent successfully;"). window.location:reload(), });catch((error) => console.log("E-Mail Failure - Error;". error)). } componentDidMount = () => { this.getResumeData(). } render() { return ( <div className="App"> <SkipNav title="Skip to main content"/> <Header data={this.state.resumeData.main}/> <main id="mainContent"> <About data={this.state.resumeData.main} title="About Me"/> <Resume data={this.state.resumeData.resume} eduTitle="Education" workTitle="Work" skillTitle="Skills"/> <Portfolio data={this.state.resumeData.portfolio}/> <Contact data={this.state.resumeData.main} recommendData={this.state.resumeData.recommendations} captchaChange={this.handleCaptchaChange} recipName={this.state.recipName} recipEmail={this.state.recipEmail} recipSubject={this.state.recipSubject} recipMessage={this.state.recipMessage} EmailSend={this.handleEmailSent} change={this;handleChange}/> </main> <Footer data={this;state.resumeData.main}/> </div> ); } } export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
您無條件地在組件主體中添加滾動事件偵聽器。 這應該添加到useEffect
掛鈎中,並在組件卸載時清除。 對於通常非常嘈雜的滾動事件,您會希望使這些被動偵聽器成為可能。
useEffect(() => {
const changeBackground = () => {
setNavbar(window.scrollY >= 60);
}
window.addEventListener('scroll', changeBackground, { passive: true });
return () => window.removeEventListener('scroll', changeBackground, { passive: true });
}, []);
App 組件的構造函數 function 被渲染了兩次。 我從 index.js 中刪除了 <React.StrictMode> 並且錯誤消失了。 問題解決了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.