source

페이지 새로고침 시 리액트 라우터에서 location.state를 클리어하려면 어떻게 해야 합니까?

nicesource 2023. 4. 4. 21:25
반응형

페이지 새로고침 시 리액트 라우터에서 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대상 컴포넌트 내부에 있습니다.그리고 나서componentDidMountAPI 요청 액션을 디스패치하여 트랜잭션을 가져올 수 있습니다.잊지 말고 삭제해 주세요.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

반응형