【问题标题】:Handling resource not found on react router在反应路由器上找不到处理资源
【发布时间】:2020-04-18 17:24:02
【问题描述】:

我有以下路由模式:

<Router history={history}>
  <Route path="/" exact render={DashboardPage}/>
  <Route path="/accounts/:id" exact render={AccountPage} />
</Router>

const AccountPage = (props) => {
  const {match: {params}} = props;
  const id = _.toInteger(params.id);

  return (
    <Layout>
      <AccountComponent id={id}/>
    </Layout>
  )
};

我已经在商店中拥有所有现有帐户,因此无需进行 Ajax 调用来确认存在。 我的问题是:如何处理 id 与任何现有资源不匹配的情况?

【问题讨论】:

  • 我认为您需要在 AccountPage 组件中处理此问题,如果 id 不存在,请重定向到未找到的 URL。

标签: reactjs react-redux react-router react-router-dom react-router-redux


【解决方案1】:

您必须检查 AccountPage 的 componentDidMount 中的 id 是否存在,因此如果 id 不存在,它应该重定向到其他地方或向他显示另一个内容,因此您的代码应该是这样的:

export default class AccountPage extends Component { 
  componentDidMount(){
    const {match: {params}} = props;
    const id = _.toInteger(params.id);

    //existenceCheck is a function that will check the id existence  
    if(existenceCheck(id)) {
      this.props.history.push('/not-found')
    }
  }

  //render and etc
}

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 2022-12-09
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多