React路上遇到的那些问题以及解决方案
阅读原文时间:2021年04月22日阅读:1

说明:因为平时遇到的问题比较多,所以我会尽量都把每次遇到的问题更新上来。但是每次遇到问题都更新博客稍显复杂,因此,以后的问题我会在github上更新,而且也会保证更新的频率。这部分的内容会涵盖npm,react,nodejs等等

问题1:Warning: Unknown props `level` `index`, `parentMenu`, `eventKey`, `closeSubMenuOnMouseLeave`, `onItemHover`, `active, `openSubMenuOnMouseEnter` on

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 '#'

将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的时候报错

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; background-color: #ffffff} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; background-color: #ffffff; min-height: 13.0px} p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #33bbc8; background-color: #ffffff} p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #34bc26; background-color: #ffffff} p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #afad24; background-color: #ffffff} span.s1 {font-variant-ligatures: no-common-ligatures} span.s2 {font-variant-ligatures: no-common-ligatures; color: #828282} span.s3 {font-variant-ligatures: no-common-ligatures; color: #33bbc8} span.s4 {font-variant-ligatures: no-common-ligatures; color: #afad24} span.s5 {font-variant-ligatures: no-common-ligatures; color: #34bc26} span.s6 {font-variant-ligatures: no-common-ligatures; color: #c33720} span.s7 {font-variant-ligatures: no-common-ligatures; color: #000000}

ERROR in ./demos/basic.md

Module build failed: SyntaxError: Unexpected token (5:11)

3 | import { Button } from 'antd';module.exports = {

4 | "content": ["article", ["h3", "1.基本用法"], function jsonmlReactLoader() {

> 5 | return

| ^

6 |

8 |