페이지 새로고침 시 리액트 라우터에서 location.state를 클리어하려면 어떻게 해야 합니까?
저는 현재 다음과 같은 경로 변경으로 통과 중입니다.
<Link to={{
pathname:`/transactions/${props.transaction.id}`,
state: {transaction: props.transaction}
}}> View Details </Link>
내 논리는 "location.state.transaction"이 존재하면 새로운 데이터를 가져오지 말고 데이터를 가져오는 것입니다.
이제 이 결함은 페이지 새로고침이 있을 때 발생합니다.사용자가 페이지를 새로고침하면 응용 프로그램에서 새 데이터를 가져와야 합니다.새로고침이 있으면 "location.state"가 클리어 될 줄 알았는데 상태가 sessionStorage에 저장되어 있는 것 같습니다.
어떻게 하면 좋을까요?매번 새 데이터를 가져올 수 있지만 'View Details' 링크를 클릭해도 데이터를 가져올 수 없습니다.
리액트 훅을 사용하는 경우window.history
리렌더를 트리거하지 않고 직접 상태를 클리어합니다.이 방법은 RPV를 사용하는 것보다useHistory
훅의replace
컴포넌트가 재렌더되는 원인이 됩니다.
window.history.replaceState({}, document.title)
저도 이 문제에 부딪혔어요.결국 리액트라우터에서 브라우저 이력을 취득하여 특정 location.state 속성을 클리어했습니다.그래서 당신의 경우엔,transaction
제가 이걸...componentDidMount
그러면 처음 페이지에 접속한 후에는 해당 자산이 더 이상 존재하지 않게 됩니다.
import createHistory from 'history/createBrowserHistory'
...
componentDidMount(){
const history = createHistory();
if (history.location.state && history.location.state.transaction) {
let state = { ...history.location.state };
delete state.transaction;
history.replace({ ...history.location, state });
}
}
3자 라이브러리를 사용하지 않는 것이 더 나은 방법입니다.
사용할 수 있습니다.history.replace()
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md
componentDidMount(){
const {location,history} = this.props;
//use the state via location.state
//and replace the state via
history.replace()
}
리액트 라우터 V6에서는 useNavigate()를 사용하여 현재 경로의 상태를 클리어할 수 있습니다.
import React, { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
useEffect(() => {
const location = useLocation();
const navigate = useNavigate();
navigate(location.pathname, {});
// reload and pass empty object to clear state
// we can also use replace option: ..., {replace: true}
}, []);
상태를 사용한 후 빈 상태의 액션을 다시 디스패치하여 상태를 클리어합니다.
this.props.dispatch(replace({
...this.props.location,
state: undefined
});
history.replace({ state: {} })
사용자를 다른 곳으로 리다이렉트하려면history.replace({ pathname: '/profile/me', state: {} })
이게 효과가 있을 수 있는 거야.
const history = useHistory();
// consume the history.location.state and reset the state
useEffect(() => {
history.replace(`/transactions/${history.location.state.transaction.id}`, {});
}, []);
를 사용하지 않는 것이 좋습니다.location
여기에서는 prop. 단, 경로와 함께 경로(정의처)를 작성하려면:/transactions/:transactionId
, 및 를 취득하기 위해서transactionId
지지대에서props.match.params.transactionId
대상 컴포넌트 내부에 있습니다.그리고 나서componentDidMount
API 요청 액션을 디스패치하여 트랜잭션을 가져올 수 있습니다.잊지 말고 삭제해 주세요.state
링크의 소품에서 param을 얻습니다.
React Router v6에서는 다음 작업을 수행할 수 있습니다.
const location = useLocation();
const navigate = useNavigate();
const state = location.state;
// Do some stuff with the state
// ...
// Clear the state after
navigate(location.pathname, { replace: true });
현재 페이지로 이동해도 상태(이력 수정)를 지우는 것 외에는 눈에 보이는 효과가 없습니다.
useNavigate를 사용해도 상태가 리셋되지 않습니다.useEffect를 설정하기만 하면 됩니다.
...
const navigate = useNavigate()
...
useEffect(() => {
// set state here
....
},[navigate]
언급URL : https://stackoverflow.com/questions/40099431/how-do-i-clear-location-state-in-react-router-on-page-reload
'source' 카테고리의 다른 글
스프링 부트 1.4테스트: 구성 오류: @Bootstrap 선언이 여러 개 발견되었습니다.와 함께 (0) | 2023.04.04 |
---|---|
PowerShell : 필드 값으로 JSON 개체를 검색합니다. (0) | 2023.04.04 |
스프링 부트: Spring Boot Servlet이니셜라이저는 권장되지 않습니다. (0) | 2023.04.04 |
AngularJS 실패한 리소스 GET (0) | 2023.04.04 |
ASP에서 View Model을 JSON 개체로 변환하는 방법.NET MVC? (0) | 2023.04.04 |