Programing

React-Router : 경로를 찾을 수 없습니까?

crosscheck 2020. 8. 7. 07:58
반응형

React-Router : 경로를 찾을 수 없습니까?


다음을 고려하세요:

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


Dejakob의 대답이 정확하고 DefaultRoute 및 NotFoundRoute가 react-router 1.0.0에서 제거되었습니다. 별표 있는 기본 경로 가 작동하려면 현재 계층 구조 수준에서 마지막이어야 한다는 점을 강조하고 싶습니다 . 그렇지 않으면 트리에서 그 뒤에 나타나는 모든 경로와 일치합니다.

반응 라우터 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의 경우

경로 유지

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

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

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

In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.

For example:

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 path="*" component={NotFound}/>
    </Switch>
  </Router>
);

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

With the new version of React Router (using 2.0.1 now), you can use an asterisk as a path to route all 'other paths'.

So it would look like this:

<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>

This answer is for react-router-4. You can wrap all the routes in Switch block, which functions just like the switch-case expression, and renders the component with the first matched route. eg)

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

When to use exact

Without exact:

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

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

With exact:

<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/
*/}

Now if you are accepting routing parameters, and if it turns out incorrect, you can handle it in the target component itself. eg)

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

Now in ProfilePage.js

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

For more details you can go through this code:

App.js

ProfilePage.js


According to the documentation, the route was found, even though the resource wasn't.

Note: This is not intended to be used for when a resource is not found. There is a difference between the router not finding a matched path and a valid URL that results in a resource not being found. The url courses/123 is a valid url and results in a matched route, therefore it was "found" as far as routing is concerned. Then, if we fetch some data and discover that the course 123 does not exist, we do not want to transition to a new route. Just like on the server, you go ahead and serve the url but render different UI (and use a different status code). You shouldn't ever try to transition to a NotFoundRoute.

So, you could always add a line in the Router.run() before React.render() to check if the resource is valid. Just pass a prop down to the component or override the Handler component with a custom one to display the NotFound view.


I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:

if (!place) return <NotFound />;

hope that helps!

참고URL : https://stackoverflow.com/questions/32128978/react-router-no-not-found-route

반응형