javascript - 为什么react js中类函数方法不被调用?

标签 javascript reactjs react-native react-router

我正在尝试制作节点事件模块的简单示例。我看了这个视频。我正在尝试在代码笔上制作相同的示例。但它不起作用,为什么?

https://www.youtube.com/watch?v=PvjNglsyOHs&index=9&list=PLoYCgNOIyGABj2GQSlDRjgvXtqfDxKm5b

这是我的代码

http://codepen.io/naveennsit/pen/dMBVaz?editors=1010

var {EventEmitter}=events;
class Todostore extends EventEmitter {
  constructor(){
    super();
    this.todo= [{
                hse: 'asd'
            }, {
                hse: 'adas'
            }]
  }
  getAll(){
    return this.todo;
  }
}
const todostore =new Todostore;
class App extends React.Component {
    constructor(props) {
        super(props);
      console.log('----')
         this.state = {
             data:todostore.getAll()
         };
    }

    render() {
        return <ul > {
                this.state.data.map((item) => {
                    return <li 
                     > {
                        item.hse
                    } < /li>;
                })
            } <
            /ul>
    }

}

React.render( < App / > , document.getElementById('app'))

最佳答案

这里有两个问题。

一,为了将来引用,如果您要在文件中链接到 GitHub 上的一些原始 Javascript,则:

https://raw.githubusercontent.com/Gozala/events/master/events.js

会导致错误:

Refused to execute script from ... because its MIME type (text/plain) is not executable, and strict MIME type checking is enabled.

您可以使用 rawgit.com 作为解决方法

https://rawgit.com/Gozala/events/master/events.js

有关此主题的更多信息可以在此处找到:Link and execute external JavaScript file hosted on GitHub

<小时/>

第二个也是更大的问题是 Codepen(以及其他 JS Playground 类型的网站,如 JSFiddle 和 JSBin)是为客户端代码构建的。您正在链接到一个旨在在服务器端 CommonJS 环境(例如 Node.js)中使用的模块。这是行不通的。

如果您的系统上安装了 Node,您应该能够通过使用 npm/bower 获取模块来在基本设置中在本地测试它:

npm install --save eventemitter3 

并将其导入到您的测试文件中:

import {EventEmitter} from 'eventemitter3';
// Rather than: var {EventEmitter}=events;

关于javascript - 为什么react js中类函数方法不被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37335997/

相关文章:

javascript - 使用 CSS 和 Jquery 使字段显示

react-native - 将导航 Prop 从父组件传递到子组件

react-native - 应用程序在前台时不显示通知

android - 无法在 Android 模拟器 - Windows 上运行 React-Native 应用程序

android - 如何改造: translate element through whole screen on Android?

css - 使用 withStyles 和 material ui 的通用类

javascript - 使用 Javascript 中的 Dropbox Core API 将文件上传到 Dropbox

javascript - jQuery 中的 while 循环

javascript - 如何更新 meteor 中的电子邮件地址?

javascript - optgroup 标签在 Chrome 浏览器中不是粗体