您的位置:首页 > Web前端 > React

React路上遇到的那些问题以及解决方案

2017-04-01 10:52 561 查看
说明:因为平时遇到的问题比较多,所以我会尽量都把每次遇到的问题更新上来。但是每次遇到问题都更新博客稍显复杂,因此,以后的问题我会在github上更新,而且也会保证更新的频率。这部分的内容会涵盖npm,react,nodejs等等
问题1:Warning: Unknown props `level` `index`, `parentMenu`, `eventKey`, `closeSubMenuOnMouseLeave`, `onItemHover`, `active, `openSubMenuOnMouseEnter` on <div> tag. Remove these props from the element
解答:详见,但是要注意,这个仅仅是warning,如果你的网页这时候无法显示不要以为就是这个原因,一般都不是这个原因
问题:antd无法正常渲染出input搜索框
解答:请确保antd安装版本和文档版本一致
问题:antd使用Select组件时候抛出下面错误
Warning: `Select[multiple|tags|combobox]` is deprecated, please use `Select[mode]` instead.

解决方法:multiple,combox单独属性在1.2.9以后已经废弃,使用mode
问题:React应用控制台输入如下的警告
warning: Failed Context Types: Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types Check the render method of `Header`.

解决方法:我的react和react-dom版本是15.0.0,升级到最新版本15.3.0+就可以了。详细内容可以点击这里
问题2: A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
return
<div>
hello world!
</div>解答:也就是说在return后面要直接跟上div,而不要空行

问题3:Uncaught TypeError: Cannot call a class as a function
解决:请确保你的Component继承了React.Component,否则你使用React语法就会出错。

问题4:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
将loader后面的import修改为require就可以了,因为此时还没有经过babel处理,也就是修改为如下:
return 'const React = require(\'react\');\n' +
'const ReactDOM = require(\'react-dom\');\n'+
code;原来的代码为:
return 'import React from \'react\';\n' +
'import ReactDOM from \'react-dom\';\n' +
code;
问题5:can not react auxiliaryCommentBefore of null
解决方案;将babel-generator降低到6.21.0即可
问题:npm install问题
addLocal Could not install C:\Users\Administrator\Desktop\redux-form-demo

解决方法:你的package.json中肯定有相对位置,如你安装的某一个包为"../../"这种路径
问题6:TypeError: Super expression must either be null or a function, not undefined
解决:说明你extend的那个函数没有导出相应的属性
class AppGenerator extends Generators.Base{}
如果Generators没有导出Base,那么报错
问题:webpack打包错误
multiple assets emit to one file

解决方法:添加output.name添加[name]等,而不是一个固定字符串,如"common.js"
问题7:内容如下
Module build failed: Error: React Hot Loader: The Webpack loader is now exported     separately. If you use Babel, we recommend that you remove "react-hot-loader" f    rom the "loaders" section of your Webpack configuration altogether, and instead     add "react-hot-loader/babel" to the "plugins" section of your .babelrc file. If                        you prefer not to use Babel, replace "react-hot-loader" or "react-hot" with "rea ct-hot-loader/webpack" in the "loaders" section of your Webpack configuration.
    at Object.warnAboutIncorrectUsage (C:\Users\Administrator\Desktop\MyApp\node   _modules\react-hot-loader\lib\index.js:7:11)
 @ multi ./~/wds-hack?http://localhost:8080 webpack/hot/dev-server ./client.js
Child html-webpack-plugin for "index.html":

在.babelrc文件中添加如下内容:
{
"presets": [
"es2015-ie",
"stage-0"
],
"plugins": [
"add-module-exports",
"react-hot-loader/babel"//在js或者jsx中使用babel-loader加options方法
]
}取消webpack.config.js下面内容:
{
test: /\.jsx$/,
exclude :path.resolve("node_modules"),
use: [{
loader:'react-hot-loader',
options:{

}
}]
}
问题:phantomjs报错
Error during loading "karma-phantomjs-launcher" plugin:
Path must be a string. Received null
解决方案:将phantomjs-prebuilt降级为2.1.7,因为在karma-phantomjs-launcher调用了它:
var phantomSource = require('phantomjs-prebuilt').path//这里获取到的path在2.1.7中存在


问题:使用了bootstrap4的less版本报错
 Error: Can't resolve 'bootstrap/less/type.less' in 'C:\Users\Administrator\Desktop\react-universal-bucket\src\theme'
  @ C:\Users\Administrator\Desktop\react-universal-bucket\src\theme\bootstrap.config.js (line 8, column 0)
  near lines:
    @import "~bootstrap/less/scaffolding.less";
    @import "~bootstrap/less/type.less";

解决方法:点击这里,查看版本,4.0以后不存在less文件夹,所以报错
问题:karma测试报错

ReferenceError: Can't find variable: webpackJsonp 

解决方法:ReferenceError: Can't find variable: webpackJsonp,也就是去掉commonchunkplugin
问题:redux-async-connet无法获取到最新数据connect到组件上进行显示
解决方法:将下面的代码进行修改
@asyncConnect([{
deferred: true,
promise: ({store: {dispatch, getState}}) => {
if (!isLoaded(getState())) {
dispatch(loadWidgets());
}
}
}])修改为如下类型:
@asyncConnect([{
deferred: true,
promise: ({store: {dispatch, getState}}) => {
if (!isLoaded(getState())) {
return dispatch(loadWidgets());
}
}
}])也就是缺少了return(特别在集成了redux的项目中如bindActionCreator,connect等方法),导致@asyncConnect发送请求修改了state状态,但是下面的代码中state不是最新的。
@connect(
state => {
console.log("connect中的state为:",state);
//上面@asyncConnect发送请求出去没有将state传递到这里来
return {
widgets: state.widgets.data,
editing: state.widgets.editing,
error: state.widgets.error,
loading: state.widgets.loading
}

},
{save, load :loadWidgets })
问题:karma报错

Error: Cannot resolve module 'react/lib/ReactMount'

解决:参考资料Error: Cannot resolve module 'react/lib/ReactMount'   Module not found: Error: Cannot resolve module 'react/lib/ReactMount' in ...      Working with React 15   Cannot resolve module 'react/addons'
最终的解决方案在这里karma.config.js,其实我就添加了下面这句:
externals: {
'jsdom': 'window',
'cheerio': 'window',
'react/lib/ExecutionEnvironment': true,
'react/addons': true,
'react/lib/ReactContext': 'window',
'sinon': 'window.sinon'
},
resolve: {
alias: {
actions: srcPath + '/actions/',
components: srcPath + '/components/',
sources: srcPath + '/sources/',
stores: srcPath + '/stores/',
styles: srcPath + '/styles/',
config: srcPath + '/config/test'//,
'react/lib/ReactMount': 'react-dom/lib/ReactMount'
}
}问题:Perf is not defined
解决方法:在webpack.config,js的module.rules下添加如下规则:
{
test: require.resolve('react-addons-perf'),
//此时我们window.antd与window.ANTD都是存在的
use: [{
loader: require.resolve('expose-loader'),
options: 'Perf'
},{
loader: require.resolve('expose-loader'),
options: 'perf'
}]
}
问题:react-router报错
TypeError: (0 , _reactRouter2.default) is not a function
[1]     at C:/Users/Administrator/Desktop/react-universal-bucket/src/server.js:81:25
[1]     at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\react-universal-bucket\node_modules\express\lib\router\layer.js:95:5)
将下面的代码:
import createMemoryHistory from "react-router";修改为:

import {createMemoryHistory} from "react-router";
问题:模块加载报错
Module not found: Error: Can't resolve 'react/lib/ReactTestUtils' in 'C:\Users\Administrator\Desktop\yo-my\node_modules\react-addons-test-utils'

那么因为该模块被移动到react-dom模块下面去了
解决方案:
resolve: {
alias: {
'react/lib/ReactMount': 'react-dom/lib/ReactMount',
'react/lib/ReactTestUtils': 'react-dom/lib/ReactTestUtils'
}
}问题:打包过程中遇到下面报错
ERROR in ./src/styles/app.css
Module build failed: Unknown word (5:1)

  3 | // load the styles
  4 | var content = require("!!../../../../../AppData/Roaming/npm/node_modules/webpackcc/node_modules/css-loader/index.js??ref--16-1!../../../../../AppData/Roaming/npm/node_modules/webpackcc/node_modules/postcss-loader/index.js??ref--16-2!./app.css");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
    | ^
  6 | // add the styles to the DOM
  7 | var update = require("!../../../../../AppData/Roaming/npm/node_modules/webpackcc/node_modules/style-loader/addStyles.js")(content, {});
 @ ./src/entry.js 12:12-39
 @ multi C:/Users/Administrator/AppData/Roaming/npm/~/webpackcc/~/wds-hack?http://localhost:8080 webpack/hot/dev-server ./src/entry.js
ERROR in ./src/static/header.css
Module build failed: Unknown word (5:1)
解决方案:是因为两次添加了webpack中loader来处理css/less/scss文件,导致loader重复了,所以直接去掉就可以了!
问题:material-ui报错

Getting Uncaught TypeError: Cannot read property 'prepareStyles' of undefined while trying to open a Dialog

解决方法:看看这里的demos stackoverflow github issue
问题:material-ui报错

Error: Cannot resolve module 'react/lib/EventPluginHub'#24

解决方法:升级下面的依赖
material-ui@0.16.3
react-tap-event-plugin@2.0.0
你可以查看这里问题: babel操作AST的时候报错
ERROR in ./demos/basic.mdModule build failed: SyntaxError: Unexpected token (5:11)
  3 | import { Button } from 'antd';module.exports = {  4 |   "content": ["article", ["h3", "1.基本用法"], function jsonmlReactLoader() {> 5 |     return <div>    |            ^  6 |     <Button type="primary" shape="circle" icon="search" />  7 |     <Button type="primary" icon="search">Search</Button>  8 |     <Button shape="circle" icon="search" />
 @ ./src/index.js 3:14-42 @ multi /usr/local/lib/~/webpackcc/~/wds-hack?http://localhost:8080 webpack/hot/dev-server ./src/index.jsChild html-webpack-plugin for "index.html":    chunk    {0} index.html 249 bytes [entry] [rendered]        [0] /usr/local/lib/~/webpackcc/~/html-webpack-plugin/lib/loader.js!/usr/local/lib/~/webpackcc/test/warning.html 249 bytes {0} [built]webpack: Failed to compile.
解决方法:你没有添加babel的相关插件,添加下面的内容即可。"babel": {
"presets": [
"es2015",
"react",
"stage-0"
],
"plugins": [
"add-module-exports",
[
"transform-runtime",
{
"helpers": false,
"polyfill": false,
"regenerator": true,
"moduleName": "babel-runtime"
}
]
]
}即可以添加到package.json中也可以添加到.babelrc文件中
问题:redux-form问题
warning.js:36Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

warning.js:36解决方法:
将下面的代码:
<button className="btn btn-default"
disabled={submitting} onClick={
editStop(form)
} >
<i className="fa fa-ban"/> 取消
</button>修改为:
<button className="btn btn-default"
disabled={submitting} onClick={()=>{
editStop(form)
}} >
<i className="fa fa-ban"/> 取消
</button>
也就是说使用一个函数将我们的onclick函数句柄包裹起来。可以看看下面的例子:
class ErrorSimulation extends React.Component {
constructor(props) {
super(props);
this.state = {
x : 1
};
}
sayHello(){
console.log("sayHello");
}
_changeValue(newValue){
console.log("_changeValue invoke!");
//你会发现虽然我们没有点击下面的超链接,但是这里会无限打印log,所以说react会自动执行下面的onClick表达式,从而得到真正的onclick函数句柄,
//进而导致无限修改state与reRender,直到内存溢出。因此可以是onClick={this._changeValue.bind(2)}或者onClick={()=>{this._changeValue(2)}},
//后者当react执行onClick表达式的时候得到的是一个函数
this.setState({newValue});
}
render() {
return (
<div>
<a onClick={this._changeValue.bind(2)}>Change Value</a>
<a onClick={this.sayHello()}>sayHello</a>
</div>
)
}
}
ReactDOM.render(
<ErrorSimulation name="World" />,
document.getElementById('container')
);参考资料:最重要的一篇  Why does this error exist: “Invariant Violation: Cannot update during an existing state transition” setState(...): Cannot update during an existing state transition
总结:你可以看到,我们的第二个a标签我们onClick是直接调用了函数,所以会导致无限渲染元素,导致内存溢出。而第一个a标签,我们使用了bind,所以必须点击才能触发,这才是我们想要的结果。

问题:bootstrap-loader报错了
bootstrap-loader  jQuery is not defined stackoverflow

解决方法:在bootstrap4中我们一定要添加下面的内容到webpack中
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
Tether: "tether",
"window.Tether": "tether",
Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
Button: "exports-loader?Button!bootstrap/js/dist/button",
Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
Util: "exports-loader?Util!bootstrap/js/dist/util"
})
点击查看官网
问题:打包的时候说没有extract-text-webpack-plugin插件
 Error: "extract-text-webpack-plugin" loader is used without the corresponding  plugin, refer to https://github.com/webpack/extract-text-webpack-plugin for the    

解决方法:报错其实很明显,我没有添加webpack的extract-text-webpack-plugin插件,但是我在loader中使用了extract方法。当然,在这之前请确认你的extract-text-webpack-plugin插件的版本没有问题
问题:bootstrap-loader报错
  File to import not found or unreadable: ~font-awesome/scss/_variables.scss.
Parent style sheet: stdin
      in C:\Users\Administrator\Desktop\bootstrap-loader-demo\node_modules\font-awesome-loader\font-awesome.config.js (line 1, column 1)
 @ ./~/style-loader!./~/css-loader!./~/sass-loader/lib/loader.js!./~/font-awesome-loader/font-awesome-styles.loader.js!./~/font-awesome-loader/font-awesome.config.js 4:14-135 18:2-22:4 19:20-141
 @ ./~/font-awesome-loader/index.js
 @ multi webpack-hot-middleware/client tether font-awesome-loader bootstrap-loader ./app/scripts/app

解决方案:添加了font-awesome-loader,但是没有安装font-awesome
问题:报错说require不是一个函数
TypeError: require(...) is not a function
    at Object.<anonymous> (C:\Users\Administrator\Desktop\mdw\bin\mdw:15:26)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
请看我的用法 require("../lib/DllPlugin")(program);
解决方法:因为我使用了export default而不是module.exports,所以你需要添加babel插件 "add-module-exports"。同时注意:不要在nodejs中使用export default等语法,而应该使用module.export

问题:Uncaught Error: The root route must render a single element
解决方法:请问你的组件是不是没有导出一个方法?如export default /module.export

问题:mapDispatchToProps方法报错
mapDispatchToProps() in Connect(InfoBar) must return a plain object. Instead received undefined.

@connect((state)=>({
info: state.info.data
}),(dispatch)=> {
//bindActionCreators第一个参数对象中的key在被connect过的组件中都是通过this.props来获取到的
//然后直接调用
bindActionCreators({load},dispatch)
})修改为如下内容:
@connect((state)=>({
info: state.info.data
}),(dispatch)=> {
//bindActionCreators第一个参数对象中的key在被connect过的组件中都是通过this.props来获取到的
//然后直接调用
return bindActionCreators({load},dispatch)
})
问题:violate-paginator报错
state.get().add is not a function

解决:因为violate-paginator明确指定了如下的peerDependencies:
"peerDependencies": {
"immutable": "^3.7.6",
"react": "^0.14.8 || ^15.1.0",
"react-redux": "^4.4.4 || 5.x",
"redux": "^3.4.0"
}所以将immutable.js从3.8.1降级为3.7.6即可

问题:这个问题是一个很简单的问题,但是可能报错的位置不正确导致很难找到
     message: 'Module build failed: Missed semicolon (6:1)\n\n \u001b[90m 4 | \u001b[39m margin-bottom\u001b[33m:\u001b[39m 24px\u001b[33m;\u001b[39m\n \u001b[90m 5 | \u001b[39m padding\u001b[33m:\u001b[
39m0 48px\u001b[33m;\u001b[39m\n\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 6 | \u001b[39m width\u001b[33m:\u001b[39m 100%\n \u001b[90m   | \u001b[39m\u001b[31m\u001b[1m^\u001b[22m\u001b[39m\n \u0
01b[90m 7 | \u001b[39m border\u001b[33m:\u001b[39m2px solid blue\u001b[33m;\u001b[39m\n \u001b[90m 8 | \u001b[39m\u001b[33m}\u001b[39m\n',
     details: 'Syntax Error: Missed semicolon (6:1)\n\n \u001b[90m 4 | \u001b[39m margin-bottom\u001b[33m:\u001b[39m 24px\u001b[33m;\u001b[39m\n \u001b[90m 5 | \u001b[39m padding\u001b[33m:\u001b[39m0 48
px\u001b[33m;\u001b[39m\n\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 6 | \u001b[39m width\u001b[33m:\u001b[39m 100%\n \u001b[90m   | \u001b[39m\u001b[31m\u001b[1m^\u001b[22m\u001b[39m\n \u001b[90m
 7 | \u001b[39m border\u001b[33m:\u001b[39m2px solid blue\u001b[33m;\u001b[39m\n \u001b[90m 8 | \u001b[39m\u001b[33m}\u001b[39m\n\n    at C:\\Users\\Administrator\\Desktop\\mdw\\node_modules\\postcss-loa
der\\index.js:146:22\n    at process._tickCallback (internal/process/next_tick.js:103:7)',

解决方法:我当时因为报错的位置不正确的原因,我直接去打印了webpack的Compiler对象,其中会有到底是哪一行出错的。下面是compiler中的error部分的内容,所以很显然就找到了原因了:
  error:
   { ModuleBuildError: Module build failed: Missed semicolon (6:1)

     4 |  margin-bottom: 24px;
     5 |  padding:0 48px;
   > 6 |  width: 100%
       | ^
     7 |  border:2px solid blue;
     8 | }

       at C:\Users\Administrator\Desktop\mdw\node_modules\webpack\lib\NormalModule.js:141:35
       at C:\Users\Administrator\Desktop\mdw\node_modules\loader-runner\lib\LoaderRunner.js:364:11
       at C:\Users\Administrator\Desktop\mdw\node_modules\loader-runner\lib\LoaderRunner.js:230:18
       at context.callback (C:\Users\Administrator\Desktop\mdw\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
       at C:\Users\Administrator\Desktop\mdw\node_modules\postcss-loader\index.js:146:13

问题:Object.entries is not a function
解决方案:添加babel-polyfill,但是加入这个库以后文件会增加大概70kb,所以我们不会采用这种方式;我们采用了object.entries,只要在代码前面添加:
const entries = require('object.entries');
if (!Object.entries) {
entries.shim();
}
问题:当Link中迭代一个对象的时候报错
Uncaught Error: Objects are not valid as a React child (found: object with keys {zh-CN, en-US}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Link`.

Uncaught TypeError: Cannot read property '__reactInternalInstance$nxdvao9iv2sfaq4x9z4pr2j4i' of null

我一开始的Link是这样迭代的:
<Link to={url} disabled={disabled}>
{item.title}
</Link>而我们的item.title是如下的内容:
{
"zh-CN": "典型页面",
"en-US": "Classic"
}所以报错了。所以修改成为如下就不报错了:
<Link to={url} disabled={disabled}>
{item.title["zh-CN"]}
</Link>问题:redux-form@6.x.x无法实现表格单行编辑
解决方法:请看下面的代码,也就是添加一个form而不是formKey
panels.map(panel =>
<PanelForm key={panel.uuid} formKey={panel.uuid} initialValues={panel} />
^^^^^^^
declare the form key
)参考:Multiple forms on page #28 How to embed the same redux-form multiple times on a page?,此时你看到我们的form下会有多个字段,每一个字段有values,initial,registeredFields.



注意:我们的代码是如下设计的:
<WidgetForm form={String(widget.id)} key={String(widget.id)} initialValues={widget}/> :同时reduxForm是如下的:
@reduxForm({
form: 'widget'
// enableReinitialize: true
// 那么后面的state会完全覆盖前面的
})此时你会发现我们的每一个表单都是直接挂载到form而不是form.widget下的,这是和没有指定form,也就是一个页面中只有一个表单的挂载方式是不一样的。如果只有一个表单是挂载在form/widget,而后者挂载在form下的位置通过WidgetForm的form属性指定。而上面是String(widget.id),所以是挂载到1,2,3下(id为1,2,3)

问题:React变量迭代的问题

invariant.js:44UncaughtError: Objects are not valid as a React child (found: object with keys {message, time}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `InfoBar`.

解决方法:你迭代的那个变量是一个对象,如我这里的info是一个对象但是迭代的时候我采用了{info},而它含有message和time两个属性,所以报错
问题:markdown转化为Jsonml时候出错
ERROR in ./lib/utils/data.js
Module build failed: YAMLException: can not read a block mapping entry; a multi
ine key may not be an implicit key at line 3, column 5:
    type: Feedback
        ^
    at generateError (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\l
b\js-yaml\loader.js:162:10)
    at throwError (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\lib\
s-yaml\loader.js:168:9)
    at readBlockMapping (C:\Users\Administrator\Desktop\mdw\node_modules\js-yam
\lib\js-yaml\loader.js:1041:9)
    at composeNode (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\lib
js-yaml\loader.js:1327:12)
    at readDocument (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\li
\js-yaml\loader.js:1489:3)
    at loadDocuments (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\l
b\js-yaml\loader.js:1545:5)
    at Object.load (C:\Users\Administrator\Desktop\mdw\node_modules\js-yaml\lib
js-yaml\loader.js:1562:19)
    at Object.jsYaml.parse (C:\Users\Administrator\Desktop\mdw\node_modules\yam
-front-matter\lib\js-yaml-front.js:16:21)
    at Object.jsYaml.loadFront (C:\Users\Administrator\Desktop\mdw\node_modules
yaml-front-matter\lib\js-yaml-front.js:34:19)
    at MT (C:\Users\Administrator\Desktop\mdw\node_modules\mark-twain\src\MT.js
10:19)
 @ ./tmp/entry.index.js 25:11-42

原因,是因为在key和value之间少了一个空格,如下:
category: Components
subtitle:警告提示
type: Feedback
title: Alert是因为"subtitle:"和"警告提示"之间少了一个空格,加上就没问题了!

问题:react-router报错

Uncaught TypeError: (0, _reactRouterREdux.syncHistoryWithStore) is not a function

(0 , _reactRouterRedux.routerMiddleware) is not a function解决方法:
npm install react-router-redux@4.0.8
问题:使用react-a11y时候报错
jsx报错Uncaught RangeError: Maximum call stack size exceeded

解决方法如下:
constructor(){
super();
//这个a11y必须设置到constructor上,如果是render上设置会堆栈溢出
if (process.env.NODE_ENV !== 'development'){
a11y(React);
}
}我们不要将a11y(React)放在render方法中,而是放在constructor里面!
问题:无状态组件的书写问题
Uncaught Error: Module build failed: SyntaxError: C:/Users/Administrator/Desktop/sy-template/theme/template/content/Article.jsx: Unexpected token, expected ; (8:10)

   6 |  */
   7 | export default (props)=>{
>  8 |   render(){
     |           ^
   9 |     return (
  10 |               <div>hello</div>
  11 |     )

解决:无状态组件是一个函数而不是一个类,所以不能直接写render,只要return就ok了。
export default (props)=>{
return (
<div>hello</div>
)
}问题:react迭代一个对象报错
 (node:5940) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Invariant Violation: Objects are not valid as a React child (found: object with keys {count}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Counter`.

解决方法:很显然我们迭代的是一个对象,其含有的key为{count},如下迭代:
<button onClick={()=>{increment()}}>当前点击的次数为{counter}:</button>修改为如下内容就可以了:
<button onClick={()=>{increment()}}>当前点击的次数为{counter.count}:</button>
问题:reactJS报错
ReactJs 报错 Element type is invalid: expected a string (from built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `Me`.
解决方法:我发现是我导入react-router的时候采用了如下方法:
import { Link } from 'react-router';而且我安装的react-router是4.x,所以导致报错,最后把react-router降级为3.0.2问题消失。这个问题好像大家出现的也比较多,大多数情况都是因为导入的方式与版本不匹配而导致的问题。

问题:React的setState的问题
Uncaught TypeError: Cannot read property 'setState' of null
    at handleCodeExpand (http://localhost:8090/components/alert/index.js:15093:9)

解决方法:
shouldComponentUpdate(nextProps, nextState) {
return (this.state.codeExpand || this.props.expand) !== (nextState.codeExpand || nextProps.expand);
}
handleCodeExapnd = () => {
this.setState({ codeExpand: !this.state.codeExpand });
}同时在jsx中就可以简单的如下使用:
<Icon type="down-circle-o" title="Show Code" className="collapse" onClick={this.handleCodeExapnd} />生命周期方法我们还是采用普通的写法,而我们自定义的方法采用了变量的形式~~~~

问题:使用expose-loader的时候出错
Uncaught ReferenceError: global is not defined
    at Object._hyphenPattern (jquery.js:1)
    at __webpack_require__ (bootstrap 22d237f…:691)
    at fn (bootstrap 22d237f…:114)
    at Object.<anonymous> (index.jsx:44)
    at Object.defineProperty.value (index.jsx:100)
    at __webpack_require__ (bootstrap 22d237f…:691)
    at fn (bootstrap 22d237f…:114)
    at webpackContext (index.js:22)
    at templateWrapper (routes.js:59)
    at processRoutes (routes.js:107)

解决方法:是因为我在webpack的配置中有下面这句代码,去掉就可以了。
noParse: [/jquery/],//此时jquery
你也可以参考这里问题1 问题2
问题:react+webpack报错
Warning: [react-router] Location "/" did not match any routes

这个博客强烈建议使用hashHistory,其实这不是必然的。我报错的原因是因为我的router配置有问题:

module.exports = {
routes:{
path :"/",
component:LayoutComponent,
IndexRoute:{
component:Index
},
childRoutes:[
{
path :"index",
component:Index
}}其实我应该去掉内部routes的这个key就没问题了
module.exports = {
path :"/",
component:LayoutComponent,
IndexRoute:{
component:Index
},
childRoutes:[
{
path :"index",
component:Index
}
}如果你要使用browserHistory,请在webpack中添加historyApiFallback。建议你使用这个打包工具
问题:webpack打包出错,即file-loader在打包配置文件webpack.config.js中添加了两次
对于使用file-loader来处理png/jpg等图片的时候发现其中的length不对,如下面的输出:
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 79 00 00 02 56 08 06 00 00 00 24 f3 91 42 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... >
URL-loader得到的limit: 10000
this.resourcePath= C:\Users\Administrator\Desktop\react-universal-bucket\src\containers\About\me.png
URL-loader得到的mimetype: image/png
URL-loader得到的content.length: 925619
-----------------------------------------
URL-loader得到的query: { limit: '10240' }
content=== <Buffer 6d 6f 64 75 6c 65 2e 65 78 70 6f 72 74 73 20 3d 20 5f 5f 77 65 62 70 61 63 6b 5f 70 75 62 6c 69 63 5f 70 61 74 68 5f 5f 20 2b 20 22 38 64 62 30 64 61 ... >
URL-loader得到的limit: 10240
this.resourcePath= C:\Users\Administrator\Desktop\react-universal-bucket\src\containers\About\me.png
URL-loader得到的mimetype: image/png
URL-loader得到的content.length: 82原因:我的webpackcc中也添加了对png/jpg的处理,而webpack-isomorphic-tools也添加了,所以重复多余了,所以第二次得到的content其实是第一次处理后的结果,其length只有82了!打印出上面的log的源码为如下:
var loaderUtils = require("loader-utils");
var mime = require("mime");
module.exports = function(content) {
this.cacheable && this.cacheable();
var query = loaderUtils.parseQuery(this.query);
console.log("URL-loader得到的query:",query);
var limit = (this.options && this.options.url && this.options.url.dataUrlLimit) || 0;
if(query.limit) {
limit = parseInt(query.limit, 10);
}
var mimetype = query.mimetype || query.minetype || mime.lookup(this.resourcePath);
console.log("content===",content);
console.log("URL-loader得到的limit:",limit);
console.log("this.resourcePath=",this.resourcePath);
console.log("URL-loader得到的mimetype:",mimetype);
console.log("URL-loader得到的content.length:",content.length);
console.log("-----------------------------------------");
if(limit <= 0 || content.length < limit) {
return "module.exports = " + JSON.stringify("data:" + (mimetype ? mimetype + ";" : "") + "base64," + content.toString("base64"));
} else {
var fileLoader = require("file-loader");
return fileLoader.call(this, content);
}
}
module.exports.raw = true;
问题:webpack打包错误
ERROR in chunk html [entry] app.js Conflict: Multiple assets emit to the same filename app.js

解决方法:
output:{
filename: '[name].js',
path: __dirname + '/build',
chunkFilename: '[id].[chunkhash].js'
},也就是在output里面不要使用固定的名称,添加[name]等

问题:报错说webpack的output.path不是一个绝对路径
下面正确打包的output内容
output:
[0] { path: 'C:\\Users\\Administrator\\Desktop\\react-universal-bucket\\dest',
[0] filename: '[name].js',
[0] chunkFilename: '[id].[chunkhash].js',
[0] library: '',
[0] hotUpdateFunction: 'webpackHotUpdate',
[0] jsonpFunction: 'webpackJsonp',
[0] libraryTarget: 'var',
[0] sourceMapFilename: '[file].map[query]',
[0] hotUpdateChunkFilename: '[id].[hash].hot-update.js',
[0] hotUpdateMainFilename: '[hash].hot-update.json',
[0] crossOriginLoading: false,
[0] hashFunction: 'md5',
[0] hashDigest: 'hex',
[0] hashDigestLength: 20,
[0] devtoolLineToLine: false,
[0] strictModuleExceptionHandling: false }不是window上path要替换掉"\\"的问题。其实是你要使用path.resolve或者__dirname来替换

问题:记一次React排错过程
报错信息:
Uncaught Error: Minified React error #37; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=37 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

分析:这次报错其实很容易理解,它说了访问后面的链接看到的信息就是本次报错decode的信息(如果process.env.NODE_ENV=="production"那么此时就是encode的报错信息,而process.env.NODE_ENV="development"得到的报错信息就是decode后的信息)。顺着这个思路,我设置了下面这段代码:
process.env.NODE_ENV = 'development';最后我再重新编译,得到的结果就是下面的内容了:
_registerComponent(...): Target container is not a DOM element.
是不是很容易理解,对于我的问题最后发现是因为if判断的问题,导致我这里都会使用自己的htmlTemplate,而我们的这个模版本身不含id为"react-content"的元素导致的~~~。更加有意思的是,设置了process.env.NODE_ENV="development"后,我们看到的信息就是后面链接的信息。以后记住这个就好了。之所以出现这个是因为React本身将报错信息在production模式下进行了encode  Error decoder

invariant.js:44UncaughtError: Objects are not valid as a React child (found: object with keys {message, time}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `InfoBar`.warning.js:36Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.warning.js:36Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: