react-router v4에서 history.push/Link/Redirect를 포함한 파라미터를 전달하려면 어떻게 해야 합니까?
는 어떻게 요?this.props.history.push('/page')React-Router v4는?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
은 안 돼요.var r = this; 나오는 바와 if statement는 콜백 자체의 콘텍스트를 나타냅니다.화살표 함수를 사용하고 있기 때문에 React 컴포넌트 콘텍스트를 참조합니다.
문서에 따르면:
이력 오브젝트에는 일반적으로 다음과 같은 속성과 메서드가 있습니다.
- length - (숫자이력 스택 내의 엔트리 수
- action - (문자열)현재 액션(PUSH, REPLACE 또는 POP)
위치 - (개체)현재 위치다음과 같은 속성을 가질 수 있습니다.
- pathname - (문자열)URL 경로
- search - (문자열)URL 쿼리 문자열
- hash - (문자열)URL 해시 프래그먼트
- state - (string) 로케이션 고유의 상태. 예를 들어 이 로케이션이 스택에 푸시되었을 때 push(path, state)에 제공되었습니다.브라우저 및 메모리 이력에서만 사용할 수 있습니다.
- push(path, [state]) - (function) 새로운 엔트리를 이력 스택에 푸시합니다.
- replace(path, [state]) - (function) 이력 스택의 현재 엔트리를 바꿉니다.
- go(n) - (function) 이력 스택 내의 포인터를 n개의 엔트리만큼 이동합니다.
- goBack() - (함수) go(-1)와 동등
- goForward() - (함수) go(1)와 동등
- block(프롬프트) - (기능) 네비게이션을 방해합니다.
따라서 탐색하는 동안 소품을 역사 객체에 전달할 수 있습니다.
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
이와 으로 사용할 수 있습니다.Link '''컴포넌트'''Redirect 표시
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
그 다음, 로 렌더링되는 컴포넌트에/template 루트는 이라는 소품들을 볼 수중에 있는 ''
this.props.location.state.detail
나 위치 withRouter.
문서에 따르면:
라우터와 함께
오브젝트의 속성에 할 수 .
<Route>'s을 하다withRouter고차 컴포넌트withRouter하여 같은 will will will will will will will will will will will will will will will will will will will will will will as as as will will will will will will will will will 。<Route>표현하다props: { match, location, history }.
리액트 후크(16.8 이후)와 함께 사용하기 위해 (슈밤 카트리가 제안한) 용액을 확장합니다.
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
이력 푸시를 사용한 파라미터 전달:
import { useHistory } from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: { detail: 'some_value' }
});
};
};
export default FirstPage;
'react-router-dom'에서 useLocation을 사용하여 전달된 파라미터에 액세스합니다.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
이전 버전의 경우:
history.push('/[pathToSomeWhere]', yourData);그리고 다음과 같이 관련 컴포넌트로 데이터를 가져옵니다.
this.props.location.state // it is equal to yourData새로운 버전에서는 위의 방법이 올바르게 기능하지만 새로운 방법이 있습니다.
history.push({ pathname: '/[pathToSomeWhere]', state: yourData, });그리고 다음과 같이 관련 컴포넌트로 데이터를 가져옵니다.
클래스 컴포넌트
this.props.location.state; // it is equal to yourData기능 컴포넌트
const location = useLocation(); location.state; // it is equal to yourData
나중에 사용할 필요가 있습니다.Link또는NavLink사용하는 대신 컴포넌트history.push기능.다음과 같이 사용할 수 있습니다.
<Link
to={{
pathname: '/[pathToSomeWhere]',
state: yourData
}}
>
...
</Link>
힌트:state최신 버전에서는 키 이름을 사용해야 합니다.
사용할 수 있습니다.
this.props.history.push("/template", { ...response })또는this.props.history.push("/template", { response: response })
그런 다음 구문 분석된 데이터에 액세스할 수 있습니다./template컴포넌트,
const state = this.props.location.state
URL 매개 변수를 통과해야 하는 경우
Tyler McGinnis의 훌륭한 포스트 설명이 그의 사이트에 있습니다.Link to the post
다음은 코드 예시입니다.
history.discomponent:
this.props.history.push(`/home:${this.state.userID}`)라우터의 컴포넌트에서 루트를 정의합니다.
<Route path='/home:myKey' component={Home} />홈 구성 요소:
componentDidMount(){
const { myKey } = this.props.match.params
console.log(myKey )
}
후크를 사용하여 TypeScript 반응
클래스에서
this.history.push({
pathname: "/unauthorized",
state: { message: "Hello" },
});
인증되지 않은 기능 컴포넌트
interface IState {
message?: string;
}
export default function UnAuthorized() {
const location = useLocation();
const message = (location.state as IState).message;
return (
<div className="jumbotron">
<h6>{message}</h6>
</div>
);
}
통과하다
history.push({pathname:"/yourroute",state: {_id: "0001", name: "AZ"}})
읽어주세요
import React from 'react';
const YourRoute = props=> {
const { _id, name } = (props.location && props.location.state) || {};
//_id and name will contain the passed data
.
.
.
}
다음은 작업 예시입니다.
사용자 지정 useQuery 훅을 만들었습니다.
import { useLocation } from "react-router-dom";
const useQuery = (): URLSearchParams => {
return new URLSearchParams(useLocation().search)
}
export default useQuery
로서 사용하다
const query = useQuery();
const id = query.get("id") as string
그대로 보내다
history.push({
pathname: "/template",
search: `id=${values.id}`,
});
React 16.8(withHooks) 기능 컴포넌트를 사용하려면 다음과 같이 하십시오.
다음 페이지로 전화 번호 전송
로그인.js
import { useHistory } from 'react-router-dom';
const history = useHistory();
const handleOtpVerify=(phoneNumber)=>
{
history.push("/OtpVerifiy",{mobNo:phoneNumber})
}
<button onClick={handleOtpVerify}> Submit </button>
OtpVerify.js
import useLocation from 'react-router-dom';
const [phoneNumber, setphoneNumber] = useState("")
useEffect(() => {
setphoneNumber(location.state.mobNo)
}, [location]);
return (
<p>We have sent Verification Code to your</p>
<h1>{phoneNumber}</h1>
)
react router dom 버전 6.2.1
useHistory()는 변경된useNavigate()를 폐지했습니다.
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()
onClick={() => { navigate('/OtpVerifiy',{mobNo:phoneNumber}) }}
사용할 수 있습니다.location상태를 다른 컴포넌트로 전송하기 위해 다음과 같이
소스 컴포넌트
this.props.history.push(pathComponent, sendState);
pathComponent상태를 수신하는 타깃컴포넌트
대상 컴포넌트에서 use class 컴포넌트를 사용하는 경우 다음과 같은 상태를 수신할 수 있습니다.
- Javascript 버전
constructor(props) {
this.state = this.props.location.state
}
- 타이프스크립트 버전
constructor(props: {}) {
const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
this.state = receiveState
}
보너스
수신 상태를 리셋 하는 경우.사용하다history이렇게 위치를 바꾸면
this.props.history({pathName: currentPath, state: resetState})
currentPath대상 컴포넌트 경로입니다.resetState새로운 가치 상태를 원하는 대로 선택할 수 있습니다.
라우터와 함께 사용할 필요는 없습니다.이것으로 충분합니다.
상위 페이지에서
<BrowserRouter>
<Switch>
<Route path="/routeA" render={(props)=> (
<ComponentA {...props} propDummy={50} />
)} />
<Route path="/routeB" render={(props)=> (
<ComponentB {...props} propWhatever={100} />
)} />
</Switch>
</BrowserRouter>
그런 다음 ComponentA 또는 ComponentB에서
이.이.이.이.가.역사
오브젝트, this.discl을 포함합니다.history.syslog 메서드
React 16.8+(withHooks)를 사용하려면 다음과 같이 하십시오.
import React from 'react';
import { useHistory } from 'react-router-dom';
export default function SomeFunctionalComponent() {
let history = useHistory(); // should be called inside react component
const handleClickButton = () => {
"funcionAPICALL"
.then(response => {
if (response.status >= 200 && response.status < 300) {
history.push('/template');
});
}
return ( <div> Some component stuff
<p>To make API POST request and redirect to "/template" click a button API CALL</p>
<button onClick={handleClickButton}>API CALL<button>
</div>)
}
자세한 내용은 여기를 참조해 주세요.https://reacttraining.com/react-router/web/example/auth-workflow
쿼리 매개 변수를 가져오려면 정보를 추가하십시오.
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
URLearchParams에 대한 자세한 내용은 이 링크 URLearchParams를 참조하십시오.
언급URL : https://stackoverflow.com/questions/44121069/how-to-pass-params-with-history-push-link-redirect-in-react-router-v4
'source' 카테고리의 다른 글
| REST 템플릿 교환을 모의하려면 어떻게 해야 하나요? (0) | 2023.02.12 |
|---|---|
| Angularjs 크롬 자동 완성 딜레마 (0) | 2023.02.12 |
| C#을 Oracle 데이터베이스에 연결하기 위해 필요한 최소 클라이언트 설치 공간은 얼마입니까? (0) | 2023.02.12 |
| @RestController vs @RepositoryRestResource를 사용하는 경우 (0) | 2023.02.12 |
| 일부 요소에 대해 nganimate 사용 안 함 (0) | 2023.02.12 |