我的 server.tsx 中有此文件:
...
const context = {msg: "hello world"}
const content = ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
<MuiThemeProvider theme={theme} sheetsManager={sheetsManager}>
<MuiPickersUtilsProvider utils={MomentUtils}>
<App />
</MuiPickersUtilsProvider>
</MuiThemeProvider>
</JssProvider>
</StaticRouter>
</Provider>
)
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<style id="jss-server-side">${css}</style>
</head>
<body>
<div id="root" style="overflow-x: hidden; width: 100%; margin: 0;">${content}</div>
<script src="/client_bundle.js" type="text/javascript"></script>
<script type="text/javascript">
window.__INITIAL_DATA__ = ${JSON.stringify(initialData).replace(
/</g,
'\\u003c'
)};
</script>
</body>
</html>
`
res.send(html)
...
而我的 routes.ts 中有这个:
...
{
name: 'Event Details',
exact: true,
path: '/events/:id',
component: (props: any) => {
if (typeof window != 'undefined' && window.document) {
console.log('IS BROWSER', (window as any).alert, (window as any).__INITIAL_DATA__)
}
return <h1>HELLO</h1>
},
loadData: (path: string) => {},
},
...
这是我的 App.tsx :
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, loginRequired, name, component: C }) => {
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return (
<Navbar>
{<C {...props} />}
</Navbar>
);
}} />
})}
</Switch>
</React.Fragment>
)
}
}
我的问题是我不知道如何使用InitialData来保湿我的成分!这行:
(window as any).__INITIAL_DATA__
总是打印undefined
,但是,如果我在浏览器的Web检查器中console.log,则 INITIAL_DATA 并不确定。
不知道我在这里做错了什么...非常感谢任何帮助