我正在我的服务器上渲染我的React App并且非常接近,但遇到了一个错误。我在网上搜索过,所有其他答案都没有解决这个问题。我收到错误Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(App)".
我提供了服务器代码,索引和应用程序。所有当前的答案都说要包装我所做的渲染组件,但仍然会收到错误。 /
路由呈现App Component。
服务器代码:
app.get('*', (req, res) => {
const error = () => res.status(404).send('404');
const htmlFilePath = path.join(__dirname, '../build', 'index.html');
fs.readFile(htmlFilePath, 'utf8', (err, htmlData) => {
if(err) {
error()
} else {
match({ routes, location: req.url }, (err, redirect, ssrData) => {
if(err) {
error()
} else if(redirect) {
res.redirect(302, redirect.pathname + redirect.search);
} else if(ssrData) {
const store = createStoreWithMiddleware(reducers)
const provider = react.createElement(Provider, { store: store }, [RouterContext]);
const ReactApp = renderToString(provider);
const RenderedApp = htmlData.replace('{{SSR}}', ReactApp);
} else {
error()
}
})
}
})
})
指数:
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.getElementById('root'));
应用:
class App extends Component {
componentWillMount() {
this.props.info();
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ info }, dispatch);
}
export default connect(null, mapDispatchToProps)(App);
错误:Unexpected token (8:15)
6 | switch(action.type) {
7 | case TEST_CASE:
> 8 | return { ...state, check: true };
| ^
9 | case REAL_CASE:
10 | return { ...state, check: false};
答案 0 :(得分:0)
您需要将<RouterContext />
与<Provider />
组件包装起来。您的服务器代码如下所示:
const store = createStoreWithMiddleware(reducers)
const ReactApp = renderToString(
<Provider store={store}>
<RouterContext {...ssrData} />
</Provider>
)