현재 페이지를 새로 고칠 때 componentWillUnmount()가 호출되지 않음
가 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★componentDidMount()
현재 페이지(이후 구성 요소)를 새로 고칠 때 메서드가 제대로 실행되지 않았습니다.그러나 링크를 클릭하여 내 웹사이트를 탐색하고 라우팅하는 것만으로 완벽하게 작동합니다.재페 페페 ?로 로? ?? ???어림없어.
.componentWillUnmount()
페이지를 갱신해도 트리거되지 않고 링크를 클릭하거나 웹 사이트/앱을 탐색할 수 있습니다.
「」의 componentWillUnmount()
매우 합니다.componentDidMount()
방법은 사용자에게 정보를 표시하는 데 매우 중요합니다.
는 ★★★★★가 필요하다.componentWillUnmount()
할 때 componentWillMount()
function후) 하여 해당 값에 이은 함수(리프레시에.에음음에에에에에에에에에에 。logos
컴포넌트가합니다.state variable은 state variable로 설정됩니다.구성 요소의 수명 주기 동안 언제든지 새 값이 변경되거나 수신되지 않습니다.
componentWillMount(){
if(dataReady.get(true)){
let logos = this.props.questions[0].data.logos.length > 0 ? this.props.questions[0].data.logos.filter((item) => {
if(item.logo === true && item.location !== ""){
return item;
}
}) : [];
this.setState({logos: logos});
}
};
절벽:
- 에서 하고 있습니다.
componentWillMount()
- 새로 고침 후 컴포넌트에 존재해야 함
- 문제가 , 이 는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.
componentWillUnmount()
가 되었을 때 - 도움이 필요하다
- 부탁합니다.
페이지 새로 고침 시 리액션은 정상적으로 컴포넌트를 마운트 해제할 수 없습니다.이벤트를 사용하여 새로 고칠 핸들러를 설정합니다(코드의 코멘트를 읽습니다.
class Demo extends React.Component {
constructor(props, context) {
super(props, context);
this.componentCleanup = this.componentCleanup.bind(this);
}
componentCleanup() { // this will hold the cleanup code
// whatever you want to do when the component is unmounted or page refreshes
}
componentWillMount(){
if(dataReady.get(true)){
let logos = this.props.questions[0].data.logos.length > 0 ? this.props.questions[0].data.logos.filter((item) => {
if(item.logo === true && item.location !== ""){
return item;
}
}) : [];
this.setState({ logos });
}
}
componentDidMount(){
window.addEventListener('beforeunload', this.componentCleanup);
}
componentWillUnmount() {
this.componentCleanup();
window.removeEventListener('beforeunload', this.componentCleanup); // remove the event handler for normal unmounting
}
}
use Window Unload Effect 후크
다음 기준에 따라 재사용 가능한 후크에 코드를 추출했습니다.
// The hook
const { useEffect, useRef, useState } = React
const useWindowUnloadEffect = (handler, callOnCleanup) => {
const cb = useRef()
cb.current = handler
useEffect(() => {
const handler = () => cb.current()
window.addEventListener('beforeunload', handler)
return () => {
if(callOnCleanup) handler()
window.removeEventListener('beforeunload', handler)
}
}, [callOnCleanup])
}
// Usage example
const Child = () => {
useWindowUnloadEffect(() => console.log('unloaded'), true)
return <div>example</div>
}
const Demo = () => {
const [show, changeShow] = useState(true)
return (
<div>
<button onClick={() => changeShow(!show)}>{show ? 'hide' : 'show'}</button>
{show ? <Child /> : null}
</div>
)
}
ReactDOM.render(
<Demo />,
root
)
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
또, 이 문제에 부딪쳐, 적어도 2개의 컴포넌트가 항상 정상적으로 마운트 해제되도록 할 필요가 있다는 것을 깨달았습니다.그래서 저는 마침내 포장된 컴포넌트를 항상 마운트 해제하는 상위 컴포넌트를 했습니다.
import React, {Component} from 'react'
// this high order component will ensure that the Wrapped Component
// will always be unmounted, even if React does not have the time to
// call componentWillUnmount function
export default function withGracefulUnmount(WrappedComponent) {
return class extends Component {
constructor(props){
super(props);
this.state = { mounted: false };
this.componentGracefulUnmount = this.componentGracefulUnmount.bind(this)
}
componentGracefulUnmount(){
this.setState({mounted: false});
window.removeEventListener('beforeunload', this.componentGracefulUnmount);
}
componentWillMount(){
this.setState({mounted: true})
}
componentDidMount(){
// make sure the componentWillUnmount of the wrapped instance is executed even if React
// does not have the time to unmount properly. we achieve that by
// * hooking on beforeunload for normal page browsing
// * hooking on turbolinks:before-render for turbolinks page browsing
window.addEventListener('beforeunload', this.componentGracefulUnmount);
}
componentWillUnmount(){
this.componentGracefulUnmount()
}
render(){
let { mounted } = this.state;
if (mounted) {
return <WrappedComponent {...this.props} />
} else {
return null // force the unmount
}
}
}
}
주의: 저처럼 터볼링크와 레일을 사용하고 있다면 양쪽 모두에 걸 수 있습니다.beforeunload
★★★★★★★★★★★★★★★★★」turbolinks:before-render
벤트입입니니다
이 질문의 조회수는 1,000이 넘습니다.이 문제를 어떻게 해결했는지 설명하겠습니다.
이 문제를 해결하려면 서브스크립션 또는 데이터베이스를 로드하는 상위 레벨의 컴포넌트를 생성하여 필요한 데이터를 하위 컴포넌트에 전달하기 전에 로드함으로써 사용할 필요가 완전히 없어집니다.componentWillMount()
또, 상위 레벨의 컴포넌트에서 계산을 실시해, 수신 컴포넌트에 사용하는 소품으로 전달할 수도 있습니다.
예를 들어 다음과 같습니다.
class UpperLevelComponent extends React.Component {
render() {
if(this.props.isReady) {
return(<ChildComponent {...props}/>)
}
}
}
export default createContainer(() => {
const data = Meteor.subscribe("myData");
const isReady = data.ready();
return {
isReady,
data: MyData.find.fetch()
}
})
위의 예에서는 Meteor의 반응형 컨테이너를 사용하여 MongoDB 데이터를 가져오고 서브스크립션이 완전히 완료될 때까지 기다렸다가 자 컴포넌트를 렌더링하여 원하는 소품을 전달합니다.상위 레벨의 컴포넌트에 모든 데이터를 로드하면componentWillMount()
새로 고침 후 트리거하는 메서드입니다.데이터는 상위 수준 구성 요소에서 준비되므로 하위 구성 요소에서 원하는 대로 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/39084924/componentwillunmount-not-being-called-when-refreshing-the-current-page
'programing' 카테고리의 다른 글
Oracle의 단일 문에 외부 키 제약 조건이 있는 새 열을 추가하는 방법 (0) | 2023.03.17 |
---|---|
Wordpress 특집 이미지 "alt" 가져오기 (0) | 2023.03.17 |
JObject 작성 시 인수 예외 (0) | 2023.03.17 |
Bootstrap-UI 자동 검색 결과 목록에 둘 이상의 속성을 표시하시겠습니까? (0) | 2023.03.17 |
로컬 패키지json은 있지만 node_module이 없습니다. (0) | 2023.03.17 |