1. 程式人生 > >React路上遇到的那些問題以及解決方案

React路上遇到的那些問題以及解決方案

說明:因為平時遇到的問題比較多,所以我會盡量都把每次遇到的問題更新上來。但是每次遇到問題都更新部落格稍顯複雜,因此,以後的問題我會在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.Receivednull
解決方案:將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 

問題: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'   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報錯

問題:material-ui報錯

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

解決方法:升級下面的依賴
[email protected]
[email protected]
你可以檢視這裡

問題: babel操作AST的時候報錯

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<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.js

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

總結:你可以看到,我們的第二個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

解決方法:因為我使用了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>

問題:[email protected]無法實現表格單行編輯

解決方法:請看下面的程式碼,也就是新增一個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 [email protected]

問題:使用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`.