reactjs - 404 page - and language param missing ha

2019-06-09 04:32发布

问题:

I am new to reactjs - working on a site with a language switch I am trying to create an error component to use as a 404 page - but also trying to see how to configure/automatically switch the site to use a default language if the parameter is not defined or to set the error path to still listen out for the lang param.

router.js currently looks like this

    <Switch>
                    <Route exact path='/' render={() => (<Redirect to='/de/dienstleistungen/geistiges-eigentum' />)} />
                    <Route path='/:langURL/services' component={Services} />
                    <Route path='/:langURL/dienstleistungen' component={Services} />
                    <Route path='/services' component={Services} />
                    <Route path='/:langURL/how-it-works' component={HowItWorks} />
                    <Route path='/:langURL/anleitung' component={HowItWorks} />
                    <Route path='/:langURL/features' component={Features} />
                    <Route path='/:langURL/funktionen' component={Features} />
                    <Route path='/:langURL/beliebte-projekte' component={BundleDetails} />
                    <Route path='/:langURL/popular-projects' component={BundleDetails} />
                    <Route component={Error} />
</Switch>

回答1:

I think you're saying the problem is that you want the user to be able to not provide the language parameter in the URL? And that right now if they don't provide it they're thrown into the Error component? You can make that parameter optional by using :langURL?:

<Switch>
    <Route exact path='/' render={() => (<Redirect to='/de/dienstleistungen/geistiges-eigentum' />)} />
    <Route path='/:langURL?/services' component={Services} />
    <Route path='/:langURL?/dienstleistungen' component={Services} />
    <Route path='/services' component={Services} />
    <Route path='/:langURL?/how-it-works' component={HowItWorks} />
    <Route path='/:langURL?/anleitung' component={HowItWorks} />
    <Route path='/:langURL?/features' component={Features} />
    <Route path='/:langURL?/funktionen' component={Features} />
    <Route path='/:langURL?/beliebte-projekte' component={BundleDetails} />
    <Route path='/:langURL?/popular-projects' component={BundleDetails} />
    <Route component={Error} />
</Switch>