加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-router – 动态路径段OR 404

发布时间:2020-12-15 09:34:10 所属栏目:百科 来源:网络整理
导读:我有一个应用程序需要在呈现404之前检查后端API.路由流程的工作方式如下: 请求进入/ {INCOMING_PATH},应用程序尝试从api.com/pages/{INCOMING_PATH}获取和呈现数据. 如果API返回404,则应用应返回404.如果不是,则呈现数据. 我不会因为这个用例而被出售. {INC
我有一个应用程序需要在呈现404之前检查后端API.路由流程的工作方式如下:

请求进入/ {INCOMING_PATH},应用程序尝试从api.com/pages/{INCOMING_PATH}获取和呈现数据.

如果API返回404,则应用应返回404.如果不是,则呈现数据.

我不会因为这个用例而被出售. {INCOMING_PATH}将是动态的,可能在路径中使用斜杠和扩展名.这是否可以在React Router中实现(具有适当的SSR行为)?如果是这样,我该怎么办?

(This question was originally posted on github由另一个用户.他们被要求在这里发布,因为它是一个支持请求.但它似乎没有.我现在陷入完全相同的问题.)

解决方法

我用 React Nested Status模块解决了这个问题.

我正在使用https://github.com/erikras/react-redux-universal-hot-example所以这个代码适合于此.有关更通用的解决方案,请参见React Nested Status.

编辑server.js:

在顶部

import NestedStatus from 'react-nested-status';

在底部替换:

const status = getStatusFromRoutes(routerState.routes);
if (status) {
  res.status(status);
}
res.send('<!doctype html>n' +
  ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));

有:

const repsonse = ReactDOM.renderToString(
  <Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>
);

const status = getStatusFromRoutes(routerState.routes);
if (status) {
  res.status(status);
}

const nestedStatus = NestedStatus.rewind();
if (nestedStatus !== 200) {
  res.status(nestedStatus);
}

res.send('<!doctype html>n' + repsonse);

然后,您需要为404服务的容器/组件:

import React,{ Component,PropTypes } from 'react';
import { connect } from 'react-redux';
import connectData from 'helpers/connectData';
import { fetchApiData } from 'redux/modules/foo/fetchApiData';
import { NotFound } from 'containers';

@connectData(null,(getReduxState,dispatch,state,params) => {
  return dispatch(fetchApiData(params.fooId));
})
@connect(
  (reduxState) => ({
    fooData: reduxState.foo.data,})
)
export default class ProductType extends Component {
  static propTypes = {
    fooData: PropTypes.object,}

  render() {
    let content;
    // ... whatever your api sends back to indicate this is a 404
    if (!this.props.fooData.exists) {
      content = <NotFound/>;
    } else {
      content = (
        <div className={styles.productType}>
          Normal content...
        </div>
      );
    }
    return content;
  }
}

最后替换/src/containers/NotFound/NotFound.js

import React,{ Component } from 'react';
import NestedStatus from 'react-nested-status';

export default class NotFound extends Component {

  render() {
    return (
      <NestedStatus code={404}>
        <div className="container">
          <h1>Error 404! Page not found.</h1>
        </div>
      </NestedStatus>
    );
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读