我是 Redux 的新手,当我使用 redux 进行服务器端渲染时,它抛出了这个错误
Invariant Violation: Could not find "store" in either the context or props of "Connect(KnowStatus)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(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')
});
最佳答案
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>
)
// ...
})
关于node.js - 不变违规 : Could not find "store" in either the context or props of "Connect(KnowStatus)". 将根组件包装在 <Provider> 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41021766/