【问题标题】:Invariant Violation: Could not find "store" in either the context or props of "Connect(KnowStatus)". Either wrap the root component in a <Provider>不变违规:在“连接(KnowStatus)”的上下文或道具中找不到“商店”。将根组件包装在 <Provider>
【发布时间】:2017-04-22 15:36:54
【问题描述】:

我是 Redux 的新手,当我使用 redux 进行服务器端渲染时,它抛出了这个错误

不变违规:在上下文中找不到“商店”或 “连接(KnowStatus)”的道具。要么将根组件包装在 , 或明确地将“商店”作为道具传递给 “连接(知道状态)”。

当我不使用服务器渲染时它工作正常但是当我使用它时会抛出这样的错误......

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')
});

【问题讨论】:

    标签: node.js reactjs redux


    【解决方案1】:

    match 函数返回的renderProps 仅包含有关应在req.url 上呈现的路由组件的信息。您仍然需要渲染 &lt;Provider&gt; 并为其提供存储对象。

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

    【讨论】:

    • 赞一百万。我不知道我是否会想到这一点。
    • 相同。非常感谢!
    猜你喜欢
    • 2023-03-24
    • 2017-12-02
    • 2016-07-12
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2019-08-29
    相关资源
    最近更新 更多