programing

React JS - 리다이렉트 컴포넌트가 포함된 소품 통과

nicescript 2023. 3. 8. 23:42
반응형

React JS - 리다이렉트 컴포넌트가 포함된 소품 통과

소품을 어떻게 전달하면 좋을까요?Redirect컴포넌트가 URL에 노출되지 않도록 해야 할까요?

이것처럼.<Redirect to="/order?id=123 />"사용하고 있습니다.react-router-dom.

데이터를 전달할 수 있습니다.Redirect다음과 같습니다.

<Redirect to={{
            pathname: '/order',
            state: { id: '123' }
        }}
/>

액세스 할 수 있는 방법은 다음과 같습니다.

this.props.location.state.id

API 문서에서는 Redirect / History prop에서 상태 및 기타 변수를 전달하는 방법에 대해 설명합니다.

출처 : https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

먼저 App.js에서 정의한 Route의 소품을 전달해야 합니다.

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>

첫 번째 컴포넌트에서

<Redirect
            to={{
            pathname: "/test/new",
            state: { property_id: property_id }
          }}
        />

그런 다음 Redirected New Test Comp에서 원하는 장소에서 사용할 수 있습니다.

componentDidMount(props){
console.log("property_id",this.props.location.state.property_id);}

브라우저 이력 상태는 다음과 같이 사용할 수 있습니다.

<Redirect to={{
    pathname: '/order',
    state: { id: '123' }
}} />

그 후, 다음의 방법으로 액세스 할 수 있습니다.this.props.location.state.id

출처 : https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

기능 컴포넌트/후크, react-router-dom 버전 5.2.0 및 기능 및 일반 소품 모두:

@Barat Kumar answer를 사용하면 Redirect를 사용하여 소품으로 기능 전달 및 접근 방법을 볼 수 있습니다.property_id 프로포트에 액세스하는 방법에도 차이가 있습니다.

경로는 동일합니다.

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>

리다이렉트:

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    state: { property_id: property_id }
  }}
/>

NewTestComp 내의 두 소품 모두 접근:

 useEffect(() => {
   console.log(props.history.location.testFunc);
   console.log(props.history.location.state.property_id);          
 }, []);

"상태"는 클래스 컴포넌트에서의 사용에서 유래한 것입니다.여기에서는 원하는 이름을 사용할 수 있고, 우리가 기능했던 것처럼 일반 소품도 전달할 수 있습니다.따라서 @Barat Kumar accepted 답변에서 조금 더 벗어나면 다음과 같이 할 수 있습니다.

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    propetries: { property_id: property_id1, property_id2: property_id2},
    another_prop: "another_prop"
  }}
/>

다음과 같은 항목에 액세스합니다.

console.log(props.history.location.testFunc);
console.log(props.history.location.propetries.property_id1);
console.log(props.history.location.propetries.property_id2);
console.log(props.history.location.another_prop);
<Redirect to={{
    pathname: '/path',
    state: { id: '123' }
}} />

그 후, 다음의 방법으로 액세스 할 수 있습니다.this.props.location.state.id원하는 컴포넌트로

  • 같은 목적으로 전용 후크를 사용할 수 있습니다.
import { createBrowserHistory } from "history";

const withRefresh = createBrowserHistory({ forceRefresh: true });
const ROOT_PATH = process.env.PUBLIC_URL || "/myapp";

const useRedirectToLocation = (params="1") => {
if(params){
withRefresh.push({
    pathname: `${ROOT_PATH}/create`,
    state: { id: `${params}` }
  });
}
} 

export default  useRedirectToLocation;

  • 다음과 같이 사용합니다.

 import useRedirectToLocation from  './useRedirectToLocation


const handleOnClick = params => useRedirectToAccounting(params)

const RedirectorComponent = () => <a onClick={handleOnClick}>{"Label"}</a>

** 요건에 따라 리팩터링할 수 있습니다.

언급URL : https://stackoverflow.com/questions/52064303/reactjs-pass-props-with-redirect-component

반응형