I am ...">

Invariant violation: could not find the "repository" in the context or props "Connect (KnowStatus)". Or wrap the root component in <Provider>

I am new to Redux. When I do server-side rendering using redux, I selected this error

Invariant violation: could not find the "repository" in the context or the details "Connect (KnowStatus)". Either wrap the root component in, or explicitly pass the "store" as a support for "Connect (KnowStatus)."

When I do not use serveriderendering, it works fine. But when I use it, it gives an error similar to this ...

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') }); 
+5
source share
1 answer

renderProps returned by the match function contains only information about route components that should be displayed on req.url . You still need to display <Provider> and provide it with a store object.

 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> ) // ... }) 
+7
source

Source: https://habr.com/ru/post/1260936/


All Articles