首页 > 解决方案 > 在反应路由器上找不到处理资源

问题描述

我有以下路由模式:

<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 与任何现有资源不匹配的情况?

标签: reactjsreact-reduxreact-routerreact-router-domreact-router-redux

解决方案


您必须检查componentDidMountAccountPage 中的 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
}

推荐阅读