【问题标题】:How to prevent Router from accessing routed without valid id?如何防止Router在没有有效ID的情况下访问Routed?
【发布时间】:2020-11-02 02:34:10
【问题描述】:

在我的 App.js 文件中,我使用了这个 Switch 逻辑:

              <Switch>
                <Route path='/' exact component={Dashboard}/>
                <Route path='/question/:id' exact component={QPage}/>
                <Route path='/new' exact component={CreateQ}/>
                <Route path='/leaderboard' exact component={Leaderboard}/>
                <Route component={Error}/> 
              </Switch>

上面的代码按预期工作。我唯一的问题是,当路由器访问 /question/:id 并因此呈现 QPage 组件时。然后,React 抛出未定义的错误,因为在 QPage 组件内部,元素尝试访问 id 和其他道具(它们从 url 中取出)。 如何防止Router访问id无效的路由?

【问题讨论】:

  • 你不能,你怎么知道它们是无效的?处理页面上的
  • 我有一个在后台运行的数据库。当我通过 UI 访问 QPage 组件时,传递了一个有效的 id,因为问题存在。我的问题是当我在不存在的 url 中键入不同的 id 时。但你可能是对的。看起来我必须处理组件内的无效 id。还是谢谢

标签: reactjs react-redux react-router router


【解决方案1】:

想到了两个选项,都依赖于历史包:

  1. 将 Qpage 组件包装在 Error Boundaries 类中,并在 componentDidCatch 方法 https://reactjs.org/docs/error-boundaries.html 中调用 history.goBack()

  2. 在 Qpage 的 componentDidMount 中,如果 API 未能返回问题,则调用 history.goBack()。此外,围绕存储 API 结果的 state 属性有条件地呈现返回。

{!this.state.property? <div/> : <div> . . . </div>}

如果 React-Router-DOM 是 5.2.0,请确保使用历史版本 4.10.1

history.js

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {Router} from 'react-router-dom'
import history from './history.js'

ReactDOM.render(
    <Router history={history}>
        <App />
    </Router>,
    document.getElementById('root')
)

Qpage 或错误边界

import history from './history'

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2013-08-17
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多