更新 2:是我的设置出现问题。我使用yarn升级react-scripts
将react-scripts
升级到版本1.0.2(原为0.9.5),现在它实际上又可以工作了。
更新:我开始认为这是我的 node.js 设置的问题。 即使是较旧的提交(我确信以前有效)也不再有效。我对 git bisect 没有任何进展(尽管我很高兴我了解了它)。
<小时/>我相当确定我不是唯一一个遇到这个问题的人,因为我不止一次看到这个问题被问过。然而,到目前为止提供的答案都没有帮助我解决这个问题。
我有一个 React 应用程序,在 render()
中失败(在 index.js
中):
render(
<Provider store={store}>
<Router
routes={config.router.routes}
history={browserHistory}
/>
</Provider>,
document.getElementById('root')
);
函数的最后一行返回null
。在 Chrome 开发者控制台中,这一点变得很清楚(我添加了 console.log
以显示结果为 null
):
很明显,由于 render()
获取 null
作为第二个参数,因此发生了特定错误。
但是,我一生都找不到它为什么返回null
。我很高兴地一直在编码,直到昨晚的某个时候它停止工作了。我的 public/index.html
如下所示:
<!doctype html>
<html lang="en">
<head>
<script>
window.settings = {
"apiUrl": "https://api.goes.here",
"imgUrl": "https://api.goes.here"
};
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>
(我已经清除了实际的 api 值。)
我也不认为这有什么问题。现在,考虑到问题是突然发生的,我可能错过了一些非常明显的事情。为了完整起见,以下是我的依赖项:
"devDependencies": {
"react-scripts": "^0.9.5"
},
"dependencies": {
"bootstrap": "^3.3.7",
"classnames": "^2.2.5",
"compression": "^1.5.2",
"firebase": "^4.0.0",
"jquery": "^3.2.1",
"linc-profile-generic-react-redux-routerv3": "^3.4.2",
"prop-types": "^15.5.8",
"query-string": "^4.3.2",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-helmet": "^5.0.3",
"react-redux": "^5.0.4",
"react-router": ">=3.0.0 <4.0.0",
"react-spinkit": "^2.1.1",
"redux": "^3.6.0",
"redux-form": "^6.7.0",
"redux-logger": "^3.0.1",
"redux-thunk": "^2.1.0"
},
我希望有人能对此有所启发。我已经没有主意了。
谢谢! 桑德尔
最佳答案
您应该直接使用ReactDOM.render方法;
示例:
ReactDOM.render(
<Provider store={store}>
<Router
routes={config.router.routes}
history={browserHistory}
/>
</Provider>,
document.getElementById('root')
);
如果您已经这样做了,我很抱歉,因为尚不完全清楚您是否正在尝试从类组件内执行渲染方法。
关于javascript - 在 React 应用程序中,render() 失败,因为 document.getElementById ('root' ) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095499/