从服务层路由 React 组件

Routing the React component from the service layer

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById('root'));

我正在使用服务层与网络通信 API 并集中 API 调用和 HTTP 错误处理。

export class HttpClient {

constructor(dispatch: any) {
        this.axios = require('axios');
        this._dispatch = dispatch;
    }

    public Post<T>(apiEndpoint: any, payload: T) {
        return this.axios.post(apiEndpoint, payload)
            .catch((error: any) => {
                this.HandleServerError(error);
            });
    }
}

HTTP 错误处理。

HandleServerError(error: any) {
        if (error.response.status == 500) {
            window.location.href = '/Internal-Server-Error';
        } else if (error.response.status == 401) {
            window.location.href = '/Unauthorized';
        }
        else if (error.response.status == 400) {
            window.location.href = '/BadRequest';
        }
        else
            this._dispatch({ type: 'RECEIVE_HTTP_ERROR', response: error.response.data });
    }

我不想从 HTTP 服务层使用 window.location.href。我如何使用 React 路由器来维护历史记录?

您可以在单独的文件中创建 history 对象并从该文件中导出该对象

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

App 组件中,导入 history 对象并将其设置为 Router 组件上的 history prop 的值

return (
    <Router history={history}>
       ...        
    </Router>
);

现在您可以在任何文件中导入历史对象并使用它。

P.S. Router 组件不是 BrowserRouter 作为 Router 导入的组件。它的较低级别 Router 组件采用名为 history.

的道具

有关详细信息,请参阅 react router docs

演示:

在此演示中,向 jsonplaceholder api 发出请求以获取单个待办事项。如果请求成功,则显示待办事项。如果出现错误,将使用 React 路由器历史对象显示错误组件。