我是Redux的新用户当我使用redux进行服务器端渲染时它给我带来了这个错误
不变违规:无法在上下文中找到“存储”或 “Connect(KnowStatus)”的道具。将根组件包装在一个 ,或明确地将“store”作为道具传递给 “连接(KnowStatus)”。
当我不使用serversiderendering它工作正常但是当我使用它时会引发这样的错误......
ServersiderenderExpress.js
import express from 'express';
import bodyParser from 'body-parser';
import {Server} from 'http';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {match, RouterContext} from 'react-router';
import routes from '../client/routes';
import Helmet from 'react-helmet';
import compression from 'compression';
import favicon from 'serve-favicon';
let app = express();
app.use(bodyParser.json());
app.use(compression());
app.use(favicon(__dirname + '/favicon/favicon.ico'))
app.use(express.static('public'));
app.get('*', (req, res) => {
match({routes, location: req.url}, (err, redirectLocation, renderProps)=> {
if (err) {
return res.status(500).send(err.message);
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
let markup;
let rendered = renderToString(<RouterContext {...renderProps}/>);
let head = Helmet.rewind();
if (renderProps) {
markup = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
${head.title}
${head.meta}
${head.link}
</head>
<body>
<div id="app">
${rendered}
</div>
<script src="bundle.js"></script/>
</body>
</html>`
}
res.write(markup);
res.end();
})
});
app.listen(3000, () => {
console.log('Listening')
});
答案 0 :(得分:8)
renderProps
函数返回的match
仅包含应在req.url
上呈现的路径组件的信息。您仍然需要呈现<Provider>
并为其提供商店对象。
import { createStore } from 'redux'
import { Provider } from 'react-redux'
match(..., (...) => {
// ...
// create the store like you do on the client side, giving
// it your reducer(s) and possibly an initial state
const store = createStore(reducer, initialState)
const rendered = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
// ...
})