react-reason v4에서 서로 다른 경로 경로에 동일한 구성 요소 사용
나는 아래와 같이 나의 리액션 앱에서 양식을 추가/편집하기 위한 동일한 구성 요소를 별도의 루트로 만들려고 한다.
<Switch>
<Route exact path="/dashboard" component={Dashboard}></Route>
<Route exact path="/clients" component={Clients}></Route>
<Route exact path="/add-client" component={manageClient}></Route>
<Route exact path="/edit-client" component={manageClient}></Route>
<Route component={ NotFound } />
</Switch>
이제 manageClient 구성 요소에서 쿼리 매개 변수를 구문 분석(편집 경로에서 클라이언트 ID로 쿼리 문자열을 전달함)하고 전달된 쿼리 매개 변수를 기준으로 조건부로 렌더링한다.
문제는 이것이 다시 전체 구성요소를 재마운트하지 않는다는 것이다.편집 페이지가 열리면 사용자가 구성 요소를 클릭하면 URL이 변경되지만 구성 요소가 다시 로드되지 않아 편집 페이지에 남아 있다고 가정하십시오.
이 문제를 해결할 방법이 있을까?
다른 사용key
각 경로에 대해 구성 요소를 재구축해야 한다.
<Route
key="add-client"
exact path="/add-client"
component={manageClient}
/>
<Route
key="edit-client"
exact path="/edit-client"
component={manageClient}
/>
한 가지 해결책은 인라인 기능을 컴포넌트와 함께 사용하는 것인데, 매번 새로운 컴포넌트를 렌더링하는 것이지만, 이것은 좋은 생각이 아니다.
다음과 같은 경우:
<Route exact path="/add-client" component={props => <ManageClient {...props} />}></Route>
<Route exact path="/edit-client" component={props => <ManageClient {...props} />}></Route>
더 나은 솔루션은 구성 요WillReceivePropes 라이프사이클 방법을 사용하는 것이다.ManageClient
구성 요소아이디어는 두 경로에 대해 동일한 구성요소를 렌더링하고 두 경로 간에 전환할 때마다react
구성 요소를 마운트 해제하지 않고 기본적으로 구성 요소만 업데이트한다.그러므로 만약 당신이 api 통화를 하거나 어떤 데이터가 필요하다면 경로 변경에 대해 이 방법으로 모든 것을 수행한다.
확인하려면 이 코드를 사용하여 경로 변경 시 호출되는지 확인하십시오.
componentWillReceiveProps(nextProps){
console.log('route chnaged')
}
참고: 조건을 붙이고 경로가 변경될 때만 api 호출을 수행하십시오.
<Route exact path={["/add-client", "/edit-client"]}>
<manageClient />
</Route>
참조
버전 5.2.0
https://reacttraining.com/react-router/web/api/Route/path-string-string
제 문제는 우리가common
동적 경로가 작동하지 않는 중간 경로
<Switch>
<Route key="Home" path="/home" component={Home} />
<Route key="PolicyPlan-create" path="/PolicyPlan/create" component={PolicyPlanCreatePage} />
{/* <Route key="PolicyPlan-list" path="/PolicyPlan" component={PolicyPlanListPage} /> */}
<Route key="PolicyPlan-list" path="/PolicyPlan/list" component={PolicyPlanListPage} />
<Route key="PolicyPlan-edit" path="/PolicyPlan/edit/:id" component={PolicyPlanCreatePage} />
<Route key="cardDesign" path="/cardDesign" component={cardDesign} />
<Route key="Admin-create" path="/admin/create" component={RegisterPage} />
</Switch>
따라서 코멘트와 같은 경로를 사용하지 마십시오. 이제 코드가 작동 중임
.................
this.props.history.push("/PolicyPlan/edit/" + row.PolicyPlanId);
.............
다음과 같이 경로 배열을 단일 경로 태그로 간단히 제공할 수 있다.
<Route exact path={["/add-client", "/edit-client"]} component={manageClient}></Route>
'Programing' 카테고리의 다른 글
잘못된 URL 매개 변수를 사용하여 404 페이지로 리디렉션하는 방법 (0) | 2022.03.10 |
---|---|
ngrx/효과 라이브러리의 목적은? (0) | 2022.03.10 |
페이지 다시 로드에서 매개 변수가 작동하지 않는 vue-properties 경로 (0) | 2022.03.09 |
Vuejs v-select에서 개체의 속성에 액세스하는 방법 (0) | 2022.03.09 |
Vue JS는 다른 계산 속성의 각 키 값에 대해 계산된 속성 실행 (0) | 2022.03.09 |