React-Router : 경로를 찾을 수 없습니까? 고려하세요: var AppRoutes

다음을 고려하세요:

var AppRoutes = [
    <Route handler={App} someProp="defaultProp">
        <Route path="/" handler={Page} />
    </Route>,

    <Route  handler={App} someProp="defaultProp">
        <Route path="/" handler={Header} >
            <Route path="/withheader" handler={Page} />
        </Route>
    </Route>,

    <Route handler={App} someProp="defaultProp">
        <Route path=":area" handler={Area} />
        <Route path=":area/:city" handler={Area} />
        <Route path=":area/:city/:locale" handler={Area} />
        <Route path=":area/:city/:locale/:type" handler={Area} />
    </Route>
];

동일한 핸들러 (앱 템플릿 내)가있는 앱 템플릿, HeaderTemplate 및 매개 변수화 된 경로 집합이 있습니다. 뭔가 찾을 수 없을 때 404 경로를 제공하고 싶습니다. 예를 들어 / CA / SanFrancisco는 Area에서 찾아서 처리해야하는 반면 / SanFranciscoz는 404입니다.

경로를 빠르게 테스트하는 방법은 다음과 같습니다.

['', '/', '/withheader', '/SanFranciscoz', '/ca', '/CA', '/CA/SanFrancisco', '/CA/SanFrancisco/LowerHaight', '/CA/SanFrancisco/LowerHaight/condo'].forEach(function(path){
    Router.run(AppRoutes, path, function(Handler, state){
        var output = React.renderToString(<Handler/>);
        console.log(output, '\n');
    });
});

문제는 / SanFranciscoz가 항상 Area 페이지에서 처리되지만 404를 원한다는 것입니다. 또한 NotFoundRoute를 첫 번째 경로 구성에 추가하면 모든 Area 페이지 404가됩니다.

<Route handler={App} someProp="defaultProp">
    <Route path="/" handler={Page} />
    <NotFoundRoute handler={NotFound} />
</Route>,

내가 뭘 잘못하고 있죠?

다음은 다운로드하고 실험 할 수있는 요점입니다.

https://gist.github.com/adjavaherian/aa48e78279acddc25315



답변

React-router 1.0.0에서 DefaultRoute 및 NotFoundRoute가 제거되었습니다.

별표 있는 기본 경로 가 작동하려면 현재 계층 구조 수준에서 마지막이어야 한다는 점을 강조하고 싶습니다 . 그렇지 않으면 첫 번째이고 모든 경로와 일치하기 때문에 트리에서 그 뒤에 나타나는 다른 모든 경로를 재정의합니다.

반응 라우터 1, 2 및 3의 경우

404를 표시 하고 경로를 유지 하려는 경우 (NotFoundRoute와 동일한 기능)

<Route path='*' exact={true} component={My404Component} />

404 페이지를 표시하고 싶지만 URL을 변경 (DefaultRoute와 동일한 기능)

<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />

여러 수준의 예 :

<Route path='/' component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path='/users' component={MyComponent}>
        <Route path='user/:id' component={MyComponent} />
        <Route path='*' component={UsersNotFound} />
    </Route>
    <Route path='/settings' component={MyComponent} />
    <Route path='*' exact={true} component={GenericNotFound} />
</Route>

반응 라우터 4 및 5의 경우

경로 유지

<Switch>
    <Route exact path="/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

다른 경로로 리디렉션 (URL 변경)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

순서가 중요합니다!


답변

최신 버전의 react-router 에서는 첫 번째 일치 된 구성 요소 만 렌더링 하는 Switch에서 경로래핑 하려고합니다 . 그렇지 않으면 여러 구성 요소가 렌더링되는 것을 볼 수 있습니다.

예를 들면 :

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  browserHistory,
  Switch
} from 'react-router-dom';

import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';

const Root = () => (
  <Router history={browserHistory}>
    <Switch>
      <Route exact path="/" component={App}/>
      <Route path="/welcome" component={Welcome}/>
      <Route component={NotFound}/>
    </Switch>
  </Router>
);

ReactDOM.render(
  <Root/>,
  document.getElementById('root')
);


답변

새 버전의 React Router (현재 2.0.1 사용)를 사용하면 모든 ‘다른 경로’를 라우팅하는 경로로 별표를 사용할 수 있습니다.

따라서 다음과 같이 보일 것입니다.

<Route route="/" component={App}>
    <Route path=":area" component={Area}>
        <Route path=":city" component={City} />
        <Route path=":more-stuff" component={MoreStuff} />
    </Route>
    <Route path="*" component={NotFoundRoute} />
</Route>


답변

이 답변은 react-router-4입니다.
switch-case 표현식처럼 작동하는 Switch 블록의 모든 경로를 래핑하고 첫 번째 일치 경로로 구성 요소를 렌더링 할 수 있습니다. 예)

<Switch>
      <Route path="/" component={home}/>
      <Route path="/home" component={home}/>
      <Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>

사용시기 exact

정확하지 않음 :

<Route path='/home'
       component = {Home} />

{/* This will also work for cases like https://<domain>/home/anyvalue. */}

정확함 :

<Route exact path='/home'
       component = {Home} />

{/*
     This will NOT work for cases like https://<domain>/home/anyvalue.
     Only for https://<url>/home and https://<domain>/home/
*/}

이제 라우팅 매개 변수를 승인하고 올바르지 않은 것으로 판명되면 대상 구성 요소 자체에서 처리 할 수 ​​있습니다. 예)

<Route exact path='/user/:email'
       render = { (props) => <ProfilePage {...props} user={this.state.user} />} />

이제 ProfilePage.js에서

if(this.props.match.params.email != desiredValue)
{
   <Redirect to="/notFound" component = {GenericNotFound}/>
   //Or you can show some other component here itself.
}

자세한 내용은 다음 코드를 참조하십시오.

App.js

ProfilePage.js


답변

문서 에 따르면 리소스가 없더라도 경로 발견되었습니다.

참고 : 이것은 리소스를 찾을 수 없을 때 사용하기위한 것이 아닙니다. 일치하는 경로를 찾지 못하는 라우터와 리소스를 찾을 수없는 유효한 URL 사이에는 차이가 있습니다. url course / 123은 유효한 url이고 일치하는 경로를 생성하므로 라우팅에 관한 한 “발견”되었습니다. 그런 다음 일부 데이터를 가져 와서 코스 123이 존재하지 않음을 발견하면 새로운 경로로 전환하고 싶지 않습니다. 서버에서와 마찬가지로 계속해서 URL을 제공하지만 다른 UI를 렌더링하고 다른 상태 코드를 사용합니다. NotFoundRoute로 전환하려고하면 안됩니다.

따라서 리소스가 유효한지 확인 Router.run()하기 React.render()위해 항상 이전 에 줄을 추가 할 수 있습니다 . 구성 요소에 소품을 전달하거나 Handler사용자 지정 항목으로 구성 요소를 재정 의하여 NotFound보기를 표시합니다.


답변

방금 귀하의 예를 간략히 살펴 보았지만 올바른 방식으로 이해했다면 동적 세그먼트에 404 경로를 추가하려는 것입니다. 며칠 전에 같은 문제가 발생하여 # 458# 1103을 발견 하고 렌더링 기능 내에서 손으로 만든 확인으로 끝났습니다.

if (!place) return <NotFound />;

도움이 되길 바랍니다!


답변