我尝试将数组导入到我的父组件中,并将该数据作为道具发送给他的孩子
import Seed from './const/Seed';
export default class ProductList extends React.Component{
render() {
const product = Seed.products[0]
return(
<div>
<Product
id = {product.id}
title = {product.title}
/>
</div>
);
}
}
我收到一个错误: TypeError:无法读取属性&#39; 0&#39;未定义的
也许我没有格式化正确的方式? 或者有没有办法在不同的文件上声明一个const?
export default class Seed extends React.Component{
render(){
const products = [
{
id: 1,
title: 'Yellow Pail',
},
{
id: 2,
title: 'Green Pail',
}
]
return products
}
}
谢谢
答案 0 :(得分:5)
种子文件应为:
export const products = [
{
id: 1,
title: 'Yellow Pail',
},
{
id: 2,
title: 'Green Pail',
},
]
export default {
products,
}
并将它们导入为(和用法):
import {products} from './const/Seed';
export default class ProductList extends React.Component{
render() {
const product = products[0]
return(
<div>
<Product
id = {product.id}
title = {product.title}
/>
</div>
);
}
}
render
方法用于在浏览器上呈现内容,而不是用于导出常量。请再次审核react / JavaScript