2016-04-26 169 views
0

我練習反應
我遇到了這個錯誤:Uncaught ReferenceError: ReactDOM is not defined
當鉻控制檯類型ReactDOM.unmountComponentAtNode(document.body)ReactDOM.unmountComponentAtNode:未捕獲的ReferenceError:ReactDOM沒有定義

請幫我查一下這個問題
我試穿的代碼JSbin和運行良好,所以我認爲這是webpack的問題,但我不知道。

而我注意到有很多方法寫React.render部分當我谷歌,有什麼區別?哪一個是正確的?

React.render(<App name='Vipul' />,document.body); 
ReactDOM.render(<App name='Vipul' />,document.body); 
React.renderComponents(<App name='Vipul' />,document.body); 

這裏是我的代碼:

main.jsx

import React from 'react'; 
import ReactDOM from 'react-dom'; 

console.log('Start') 
var App = React.createClass({ 
    render: function(){ 
    console.log('render'); 
    return <h1 onClick={this.toggleState}>Hello</h1> 
    }, 
    componentWillUnmount: function(){ 
    //在console執行 ReactDOM.unmountComponentAtNode(document.body) 
    console.log('componentWillUnmount'); 
    }, 

    toggleState: function(){ 
    this.setState({status: !this.state.status}) 
    } 

}); 

ReactDOM.render(<App name='Vipul' />,document.body); 

webpack.config.js

var WebpackNotifierPlugin = require('webpack-notifier'); 

module.exports = { 
    entry: "./src/main.js", 
    output: { 
     filename: "./dist/bundle.js" 
//  filename: "./public/dist/bundle.js" 
    }, 
    plugins: [ 

    new WebpackNotifierPlugin() 

    ], 
    module: { 
     loaders: [ 
      { 
       test: /\.jsx?$/, 
       exclude: /node_modules/, 
       loader: "babel-loader", 
       query: { 
        presets: ['es2015', 'react'] 
       } 
      } 
     ] 
    },devtool: 'source-map' 
}; 

回答

1

ReactDOM自0.14.0可用,所以

ReactDOM.render(<App name='Vipul' />,document.body); 

應該罰款。如果您使用的是較低版本的React,則React.render

其次,建議不要在document.body上渲染,而應在body內部創建div並在其中渲染。

I met this error : Uncaught ReferenceError: ReactDOM is not defined when type ReactDOM.unmountComponentAtNode(document.body) on chrome console

當您使用Webpack時,React和ReactDOM將不可用於全局。所以,這段代碼只能在您導入React & ReactDOM的文件/模塊內部工作。

+0

謝謝。我明白了你的觀點。如果我在我的代碼中使用'setTimeout(()=> {0} {} {}}。它運作良好!謝謝 – user2492364

0

只有一種呈現方式做出反應在瀏覽器中的組件,它是這樣的:

ReactDOM.render(<App />, target); 

所有其他已棄用 - renderComponent被重命名爲renderreact包移到react-dom包。

此外,您是否需要在您的componentWillUnmount生命週期方法中致電unmountComponentAtNode?在你的具體情況下,這是沒有意義的。 React將免費爲您卸載組件。

componentWillUnmount通常用於清除超時/間隔和/或取消異步操作(承諾,關閉連接,...);

刪除該通話不會對您造成傷害,請嘗試一下。

+0

謝謝。我使用''''setTimeout(()=> {ReactDOM.unmountComponentAtNode(document.getElementById('app'));},10000);''''在我的代碼中。它運作良好! – user2492364

相關問題