我正在使用reactjs和es6,我定义了一个javascript,如下所示。
vendor.jsx:
export const VENDOR_LIST = [{
vendor: []
}];
在另一个javasript文件中,我想导入这个文件,所以我使用了下面的代码。但我总是在 componentDidMount() 方法中遇到 VENDOR_LIST is undefined 错误。我的代码有什么问题吗?
import VENDOR_LIST from '../data/vendor'
export class VendorList extends React.Component{
selectChanged(e){
console.log('select changed ', e);
}
componentDidMount(){
console.log('load vendor list data ',VENDOR_LIST);
}
render(){
return (
<select onChange={this.selectChanged}>
<option value="A">A</option>
<option value="B">A</option>
<option value="-">Other</option>
</select>
)
}
}
最佳答案
为了更好地解释 import 语句在 ES6 中的工作原理,简而言之,它与文件中的 export
的完成方式有关。
如果您使用default
导出,那么您可以像使用任何命名变量一样导入它,因为这就是它被分配给的内容:
const foo = 'FOO';
export default foo;
import otherFoo from '/the/file';
请注意我如何不使用花括号,而是使用我想要的任何名称来定义它。
现在,如果您导出多个没有默认值的内容:
export const foo = 'FOO';
export const bar = 'BAR';
import { foo, bar as otherBar } = from '/the/file';
现在您看到您必须使用文件中声明的名称并使用花括号来导入它们。如果您想分配给不同的变量,您可以随时使用 as
表示法。
关于javascript - 在reactjs中导入模块失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563122/