ReactJs Component在cordovas onDeviceReady函数之前呈现

时间:2015-11-06 17:43:32

标签: javascript cordova reactjs

我目前正在尝试使用React JS(v.0.14)和cordova。 我想用一个带有cordova文件插件的Android模拟器的SD卡读取一些文件。

当我尝试启动应用程序时,我总是收到错误,cordova.file.*未定义。发生这种情况是因为,React组件在调用cordova onDeviceReady之前呈现。我在ReactDOM.render函数中添加了onDeviceReady函数,但该函数不起作用。

app.js

var app = {
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        console.log('on ready');    // Update DOM on a Received Event

        ReactDOM.render(
          <App />,
          document.getElementById('app')
        );
    }
};
app.initialize();

var App = React.createClass({
    getInitialState: function() {
        return {tiles:[]};
    },

    componentDidMount: function() {
        var PATH = cordova.file.externalRootDirectory + 'testdir/'; //Is called before onDeviceReady

    },

    render: function() {
        return (
            <div>
                <Navigation title="Dashboard"/>
                <Dashboard tiles={this.state.tiles}/>
            </div>
        );
    }
});

的index.html:

<body>
        <!-- fixed top navbar -->
        <div id="app">

        </div>
        <!-- Dashboard -->

        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="bower_components/react/react.js"></script>
        <script type="text/javascript" src="bower_components/react/react-dom.js"></script>
        <script type="text/javascript" src="js/browser.min.js"></script>
        <script type="text/babel" src="js/app.js"></script>
    </body>

来自控制台的错误消息是:

Uncaught TypeError: Cannot read property 'externalRootDirectory' of undefined ...
on ready 

如何在onDeviceReady之后或之后加载我的React组件?

谢谢&amp;映入眼帘, mybecks

1 个答案:

答案 0 :(得分:0)

就我而言,我正在等待设备信息。

请看一下此链接here

点击此链接后,我想出了这段代码:

function initApp () {
    ReactDOM.render(<App />, document.getElementById('root'));
};

if (window.cordova) {
    document.addEventListener("deviceready", () => {
        initApp();
    }, false);
} else {
    initApp();
}