IT이야기

라우터 v4 기본 페이지 반응(찾을 수 없음 페이지)

cyworld 2022. 3. 26. 16:34
반응형

라우터 v4 기본 페이지 반응(찾을 수 없음 페이지)

일치하지 않는 요청을 찾을 수 없는 페이지로 유도하는 것이 일반적인 목적이다.

리액터-러터 v4로 만드는 것은 이전 버전과 비슷해 보이며, 나는 이 샘플이 아래에도 효과가 있을 것으로 예상한다.링크는 잘 작동하지만, 나는 NotFound 컴포넌트가 요청된 알 수 없는 url이라고만 불릴 것으로 예상한다. 그러나 항상 거기에 있다.

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'


class Layout extends Component {
  render() {
    return (
    <Router>
      <div className="App">
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/user">User</Link></li>
        </ul>
        <Route exact path="/" component={Home}/>
        <Route path="/user" component={User}/>
        <Route path="*" component={Notfound}/>
      </div>
  </Router>
    );
  }
}

여기에 이미지 설명을 입력하십시오. 여기에 이미지 설명을 입력하십시오.

그 이후path="*"모든 요청 및 검색되지 않은 구성 요소를 항상 거기에 표시하지만 유효한 URL 경로에 대해 이 구성 요소를 숨긴다고 어떻게 말할 수 있는가?

대응 라우터의 일치 안 함 설명서에 수록된 내용은 다음과 같다.다음 항목을 가져오십시오.<Switch>구성 요소를 제거한 후path총체적으로 해석하다

A <Switch>첫째를 낳다<Route>그것과 잘 어울린다.a<Route>항상 일치하는 경로 없이

다음을 사용하는 예:

<Router>
  <div>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Redirect from="/old-match" to="/will-match"/>
      <Route path="/will-match" component={WillMatch}/>
      <Route component={NoMatch}/>
    </Switch>
  </div>
</Router>

그래서 당신 같은 경우에는 그냥 그 일을 그만두면 되는 거지요.path="*"그리고 소개하다<Switch>:

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/user" component={User}/>
  <Route component={Notfound} />
</Switch>

다음을 포함해야 함을 기억하십시오.Switch당신께import상부의 진술

이것은 두 가지 요소로 이루어진 나의 해결책이다.

const NotFound = () => <div>Not found</div>

const NotFoundRedirect = () => <Redirect to='/not-found' />

//root component
<Switch>
 <Route path='/users' component={UsersPages} />
 <Route path='/not-found' component={NotFound} />
 <Route component={NotFoundRedirect} />
</Switch>

//UsersPages component
<Switch>
 <Route path='/home' component={HomePage} />
 <Route path='/profile' component={ProfilePage} />
 <Route component={NotFoundRedirect} />
</Switch>

그 일은 내게 안성맞춤이다.고마워요.

이 방법은 완벽하게 작동하며, URL이 존재하지 않거나 거짓일 경우 리디렉션을 할 수 있다.

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/sorties-scolaires" component={SortiesScolaires} />
        <Route path="/voyages-entreprise" component={VoyagesEntreprise} />
        <Route path="*">
          <Redirect to="/" />
        </Route>
      </Switch>
    </Router>
  );
}

허용 솔루션이 해답을 제공하지만 중첩된 경로가 있으면 작동하지 않음

예를 들어 다음과 같은 경우Home구성 요소에 중첩된 경로:/home,/dashboard그리고 방문한 URL이/db, 그것은 a를 보여줄 것이다.NotFound구성 요소는 경로 섹션 내에서만 구성되며 페이지 전체는 전체적으로 구성되지 않는다.

이 문제를 방지하려면 구성 요소와 공급자를 사용하는 간단한 방법을 사용하십시오.

const NoMatch = (props) => (
    <Redirect to={{state: {noMatch: true}}} />
)

const ProviderHOC = (NotFoundRoute) => {
    const RouteProvider = (props) => {
        if(props.location && props.location.state && props.location.noMatch) {
           return  <NotFoundRoute {...props} />
        }
        return props.children;
    }
    return withRouter(RouteProvider)

}

export default ProviderHOC;

그리고 나서 이렇게 쓰면 된다.

const RouteManager  = ProviderHOC(NotFoundComponent);

<Router>
  <RouteManager>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Redirect from="/old-match" to="/will-match"/>
      <Route path="/will-match" component={WillMatch}/>
      <NoMatch />
    </Switch>
  </RouteManager>
</Router>

그리고 Home 구성 요소 내에서

render() {
    return (
         <Switch>
               <Route path="/home" component={NewHome} />
               <Route path="/dashboard" component={Dashboard} />
               <NoMatch />
         </Switch>
    )
}

라우터 v6 반응

라우터 v4에 대한 질문인 것은 알지만 v6이 아웃되어 있기 때문에 선택한 경로 중 하나로 리디렉션하고 탐색할 수 있으며,<Navigate>라우터 반응의 구성 요소.

예:

<Router>
  <Routes>
    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />
  </Routes>
</Router>

이제 다음과 같은 빈 경로에 대한 사례를 경로 구성 아래에 선언할 수 있다.

<Router>
  <Routes>
    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />
    <Route path="" element={<Navigate to="/users" />} />
  </Routes>
</Router>

실시간 데모: 기본 경로 또는 반응 라우터를 사용하여 404개 경로 리디렉션

나한테는 안 먹히는데, 특히 이 구성을 사용하는 사람이 있어.

그래서 홈페이지 컴포넌트의 렌더링 기능에서 경로를 확인해야 한다.이와 비슷한 것:

render(){
const {match, location, history} = this.props;
if (location.pathname === '/'){
return (<div>Home</div>)
}else{
return null
}
}

참조URL: https://stackoverflow.com/questions/42929472/react-router-v4-default-pagenot-found-page

반응형