【发布时间】:2017-07-08 14:53:00
【问题描述】:
我正在我的服务器上渲染我的 React 应用程序,并且非常接近,但遇到了一个错误。我在网上搜索过,所有其他答案都没有解决这个错误。我收到错误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 组件。
服务器代码:
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};
【问题讨论】:
-
你不能使用 es6 特性,比如在 vanilla 节点中传播的对象休息。您要么需要使用 webpack 编译服务器包,要么不使用该功能。
-
我安装了
babel-polyfill,并在我的服务器代码的最顶部安装了require('babel-polyfill'),但我仍然收到错误,我还需要做什么吗? -
正如安迪所说,你需要使用webpack来打包代码,或者将
require('babel-register')放在你的服务器代码的顶部,创建一个.babelrc来设置像es2015这样的预设。跨度> -
@joethemow 你需要 babel-register 来获得语法变化,polyfill 只给你像 WeakMap 这样的原生对象 blog.andrewray.me/how-to-use-es6-in-nodejs