goBack()이 라우터 v4에 응답하기 전에 이전 위치를 확인합니다.
목표는 "돌아가기" 버튼을 활성화하는 것입니다. 단, 사용자가 돌아가는 경로/경로가 특정 범주에 있는 경우에만 가능합니다.
보다 정확하게는 2종류의 루트가 있습니다./<someContent>그리고./graph/<graphId>사용자가 그래프 사이를 이동할 때 이전 그래프로 돌아갈 수 있어야 하지만/...루트를요. 이래서 그냥 도망칠 수가 없어요.history.goBack()먼저 위치를 확인해야 합니다.
const history = createHashHistory();
const router = (
<ConnectedRouter history={history}>
<Switch>
<Route exact path='/' component={Home}></Route>
<Route exact path='/extension' component={Home}></Route>
<Route exact path='/settings' component={Home}></Route>
<Route exact path='/about' component={Home}></Route>
<Route exact path='/search' component={Home}></Route>
<Route exact path='/contact' component={Home}></Route>
<Route path='/graph/:entityId' component={Graph}></Route>
</Switch>
</ConnectedRouter>
);
이러한 기능을 구현하고 싶습니다.Graph컴포넌트:
if (this.props.history.previousLocation().indexOf('graph') > -1){
this.props.history.goBack();
} else {
this.disableReturnButton();
}
이 질문은 다음에도 적용됩니다.goForward()'전송' 버튼을 비활성화 하고 싶기존에 해당되지 않는 경우.또, 유저는 다음과 같이 이동한다.this.props.history.push(newLocation)
물론 로그인 같은 사이드 트릭은 피하고 싶습니다.localStorage또는 환원store사용자가 움직이면 자연스럽지 않게 느껴지고, 어떻게 하는지 알아요.
네비게이트 중에Link컴포넌트나history.push현재 위치를 다른 곳으로 전달할 수 있습니다.Route요소
맘에 들다
<Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />
또는
history.push({
pathname: '/graph/1',
state: {
from: this.props.location.pathname
}
})
컴포넌트에서 이 위치를 얻을 수 있습니다.this.props.location.state && this.props.location.state.from그리고 나서 네가 원하지 않을지 결정해.goBack그렇지 않으면.
사용.context이전 위치를 저장할 수 있습니다.pathname:
const RouterContext = React.createContext();
const RouterProvider = ({children}) => {
const location = useLocation()
const [route, setRoute] = useState({ //--> it can be replaced with useRef or localStorage
to: location.pathname,
from: location.pathname
});
useEffect(()=> {
setRoute((prev)=> ({to: location.pathname, from: prev.to}) )
}, [location]);
return <RouterContext.Provider value={route}>
{children}
</RouterContext.Provider>
}
다음으로, 아래의 일부 컴포넌트에서는RouterProvider:
const route = useContext(RouterContext);
//...
<Link to={route.from}>
Go Back
</Link>
언급URL : https://stackoverflow.com/questions/47409586/check-history-previous-location-before-goback-react-router-v4
'programing' 카테고리의 다른 글
| 도커에 워드프레스(작성 없음) (0) | 2023.02.28 |
|---|---|
| Angular.js가 프로그래밍 방식으로 양식 필드를 더티로 설정합니다. (0) | 2023.02.28 |
| Google Instant는 어떻게 작동합니까? (0) | 2023.02.28 |
| Pymongo를 사용하여 컬렉션의 모든 문서 가져오기 (0) | 2023.02.28 |
| SQL SELECT 문에서 패키지 상수를 사용하는 방법 (0) | 2023.02.28 |