如何更正Reactj中的Uncaught RererenceError?

时间:2016-11-23 22:26:45

标签: javascript reactjs

当我添加channels数组作为在应用程序的开始阶段模拟通道列表的方法时,我开始收到此错误。

index.js:7852未捕获的ReferenceError:未定义通道(...)

这是App.js文件:

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

let channels = [
    {name: 'Hardware Support'},
    {name: 'Software Support'}
];

class Channel extends React.Component {
    onClick(){
        console.log('I was clicked', this.props.name);
    }
    render(){
        return (
            <li onClick={this.onClick.bind(this)}>{this.props.name}</li>
        )
    }
}

export default Channel

这是main.js文件:

import React from 'react';
import ReactDOM from 'react-dom';
import Channel from './App';

class ChannelList extends React.Component {
    render(){
        return (
            <ul>
                {this.props.channels.map(channel => {
                        return (
                            <Channel name={channel.name} />
                        )
                    }
                )}
            </ul>
        )
    }
}

class ChannelForm extends React.Component{
    onChange(e){
        console.log(e.target.value);
    }
    onSubmit(e){

    }
    render(){
        return (
            <form onSubmit={this.onSubmit.bind(this)}>
                <input type='text' onChange={this.onChange.bind(this)} />
            </form>
        )
    }
}

class ChannelSection extends React.Component {
    render(){
        return(
            <div>
                <ChannelList channels={channels}/>
                <ChannelForm />
            </div>
        );
    }
}

ReactDOM.render(<ChannelSection />, document.getElementById('app'));

1 个答案:

答案 0 :(得分:3)

正如@FelixKling所述,channels变量无法使用main.js变量,因为它不是从App.js导出的。在两个文件中共享此内容的最简单方法是导出为非默认导出,然后将其作为Channels导入Main.js

像这样:

// App.js
let channels = [
    {name: 'Hardware Support'},
    {name: 'Software Support'}
];

...

export channels; // this is the variable export
export default Channel; // this is the class export, which will be the default if no specific export is declared in your import

// Main.js
import Channel, { channels } from './App';
// `Channel` class is imported as usual, along with non-default `channels` export

您还应该在const声明中使用let代替channels,因为您没有重新分配。

const channels = ...