mirror of
https://github.com/zhigang1992/DefinitelyTyped.git
synced 2026-03-26 10:14:26 +08:00
Fix react router static router context bug (#29626)
* Fix bug with StaticRouterContext * Add tests for react-router
This commit is contained in:
2
types/react-router/index.d.ts
vendored
2
types/react-router/index.d.ts
vendored
@@ -88,7 +88,7 @@ export interface RouterProps {
|
||||
}
|
||||
export class Router extends React.Component<RouterProps, any> { }
|
||||
|
||||
export interface StaticRouterContext {
|
||||
export interface StaticRouterContext extends StaticContext {
|
||||
url?: string;
|
||||
action?: 'PUSH' | 'REPLACE';
|
||||
location?: object;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import * as React from 'react';
|
||||
import * as express from 'express';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { StaticRouter, Route } from 'react-router-dom';
|
||||
import { StaticRouterContext } from 'react-router';
|
||||
|
||||
interface StaticContext extends StaticRouterContext {
|
||||
statusCode?: number;
|
||||
}
|
||||
import { StaticContext, StaticRouterContext } from 'react-router';
|
||||
|
||||
interface RouteStatusProps {
|
||||
statusCode: number;
|
||||
@@ -12,9 +10,9 @@ interface RouteStatusProps {
|
||||
|
||||
const RouteStatus: React.SFC<RouteStatusProps> = (props) => (
|
||||
<Route
|
||||
render={({ staticContext }) => {
|
||||
render={({ staticContext }: {staticContext?: StaticContext}) => {
|
||||
if (staticContext) {
|
||||
(staticContext as StaticContext).statusCode = props.statusCode;
|
||||
staticContext.statusCode = props.statusCode;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -37,7 +35,7 @@ const PrintContext: React.SFC<PrintContextProps> = (props) => (
|
||||
);
|
||||
|
||||
class StaticRouterExample extends React.Component {
|
||||
staticContext: StaticContext = {};
|
||||
staticContext: StaticRouterContext = {};
|
||||
|
||||
render() {
|
||||
return (
|
||||
@@ -53,4 +51,18 @@ class StaticRouterExample extends React.Component {
|
||||
}
|
||||
}
|
||||
|
||||
const app = express();
|
||||
|
||||
app.get('*', (req, res) => {
|
||||
const staticContext: StaticRouterContext = {};
|
||||
|
||||
const html = renderToString(
|
||||
<StaticRouter location={req.url} context={staticContext}>
|
||||
(includes the RouteStatus component below e.g. for 404 errors)
|
||||
</StaticRouter>
|
||||
);
|
||||
|
||||
res.status(staticContext.statusCode || 200).send(html);
|
||||
});
|
||||
|
||||
export default StaticRouterExample;
|
||||
|
||||
Reference in New Issue
Block a user