【发布时间】:2021-12-15 07:07:42
【问题描述】:
你好,我很新,我正在练习 react。
这篇文章的 TL;DR 是我想在 react 中创建一些动态变量,但我不能。
我正在用 React 做一个商店的网页。因此,为了制作显示产品的主页,我制作了一个 Product 组件,它具有一些类似这样的属性
import React from 'react'
function Product({id,title,image,image_description,price,description}) {
return (
<div >
<div >
<p>{title}</p>
<b>{price}$</b>
<img src={image} alt={image_description}/>
<p>{description}</p>
</div>
</div>
)
}
export default Product
然后我创建了一个名为“ProductDataComponent”的组件,在其中创建了一个数组,其中包含一些具有这些属性的对象
var productData = [
// 0
{
id : 10,
title: 'Jugo de Naranja',
image: 'urlOfImage.com',
image_description: 'Juguito de naranja' ,
price: 100,
description: 'Un rico jugo de naranja'
},
//1
{
etc
}
];
export default productData
然后我在 home 组件中导入了该组件,为了使代码更干净,我制作了一些变量来获取数组的一个元素
import React from 'react'
import Product from './Product'
import './Home.css'
import productData from './ProductDataComponent'
var p0 = productData[0]
var p1 = productData[1]
function Home() {
return (
<div className='home'>
<div className="home__container">
<div className="home__row">
<Product id={p0.id} title= {p0.title} image={p0.image} image_description={p0.image_description} price={p0.price} description={p0.description}/>
<Product id={p2.id} title= {p2.title} image={p2.image} image_description={p2.image_description} price={p2.price} description={p2.description}/>
</div>
</div>
</div>
)
}
export default Home
到目前为止,代码运行良好。
问题是我想自动化变量的制作过程,所以我不必每次在 productData 数组中添加新对象时都手动编写。
我搜索了一种方法,我找到了两种方法。一个带有 eval() 方法的方法是邪恶的并且不起作用。 另一种方法是执行这样的 for 循环
var i
for (let i = 0; i < productData.length; i++) {
window['p'+i] = productData[i];
}
我在 javascript 中隔离的其他页面中测试了此方法,并且它有效,但是当我将它放入 react 的 home 组件中时,它不起作用。 这是网页显示的内容。
Failed to compile
src\Home.js
Line 32:34: 'p0' is not defined no-undef
Line 32:49: 'p0' is not defined no-undef
Line 32:66: 'p0' is not defined no-undef
Line 32:95: 'p0' is not defined no-undef
Line 32:124: 'p0' is not defined no-undef
Line 32:147: 'p0' is not defined no-undef
Line 33:34: 'p1' is not defined no-undef
Line 33:49: 'p1' is not defined no-undef
Line 33:66: 'p1' is not defined no-undef
Line 33:95: 'p1' is not defined no-undef
Line 33:124: 'p1' is not defined no-undef
Line 33:147: 'p1' is not defined no-undef
我做错了什么吗? 有没有办法动态命名变量或自动化流程?
ps:我的母语不是英语,所以请原谅我的语法错误。
【问题讨论】:
-
您似乎解决了错误的问题,您不应该将数据存储在窗口对象中。可以使用
map动态创建元素
标签: javascript reactjs variables dynamic-variables