问题
In react-router 0.13, you could pass props into a route handler, as such
serverApp.get('/*', function(req, res) {
Router.run(AppRoutes, req.url, function(Handler, state) {
var markup = React.renderToString(
<Handler path={req.url} myProps={myProps}/>
);
res.send('<!DOCTYPE html>' + markup);
});
});
Now with react-router v1.0, that has been replaced with match()
and RoutingContext
. I have not been able to get it to work. My code below:
serverApp.get('/*', function(req, res) {
match({routes: AppRoutes, location: req.url},
(error, redirectLocation, renderProps) => {
var markup;
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
var myApp = React.cloneElement(<RoutingContext {...renderProps} />, {myProps: 'OK'});
markup = renderToString(myApp);
res.status(200).send('<!DOCTYPE html>' + markup);
} else {
res.status(404).send('Not found');
}
}
);
});
This is what I thought should work, but having no success. I test it by logging out the additional prop in the render method of the component, as well as setting it in an h1 tag.
Any ideas on what I'm doing wrong here? Much appreciated.
Related: https://github.com/rackt/react-router/issues/1369
回答1:
You have to pass a method createElement
to RoutingContext
. In the createElement
method you have access to the component that will be returned. Here you can add external props that will be available to every route that mounted.
Server:
serverApp.get('/*', function(req, res) {
match({routes: AppRoutes, location: req.url},
(error, redirectLocation, renderProps) => {
var markup;
var myApp;
var createElement = function(Component, props) {
return <Component {...props} myProps="OK"/>;
};
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302,
redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
myApp = (
<RoutingContext
{...renderProps}
createElement={createElement}
/>
);
markup = renderToString(myApp);
res.status(200).send('<!DOCTYPE html>' + markup);
} else {
res.status(404).send('Not found');
}
}
);
});
React app routes:
var AppRoutes = (
<Route component={AppTemplate} path="/">
<Route component={OtherTemplate} path="/">
<Route component={FirstPage} path="/first" />
<Route />
<Route />
);
When navigating to '/first', all 3 of those components will have access to myProps via this.props.myProps
The more practical use case for this is passing a flux object into your application (instead of a simple myProps="OK").
来源:https://stackoverflow.com/questions/33978781/react-router-v1-0-passing-props-into-application-on-server