我试图在React中使用一个定义为常量的数组,并在我的App函数中传递这个数组。然而,当我尝试使用它时,我会得到一个";TypeError:产品未定义";(关于<li> {products[0].id}</li>
(。
任何帮助都将不胜感激。我已经附加了我的App.js文件,并将应用程序剥离为空,试图找出这个问题。
完整项目的链接可以在这里找到:https://github.com/coopertim13/ProblematicReact
import React, { useState } from 'react';
import ReactDOM from 'react-dom'
const products = [
{id: 'P1000', name:'UGG', category: 'Cool'}
]
const App = (props) => {
const {products} = props
return (
<div>
<ul>
<li> {products[0].id}</li>
</ul>
</div>
)
}
ReactDOM.render(
<React.StrictMode>
<App products = {products}/>
</React.StrictMode>,
document.getElementById('root')
);
export default App;
错误告诉您需要知道什么。你在App
上的道具被称为单位,但你试图从中破坏products
,也就是undefined
。
将const {products} = props
更改为const {units} = props
,然后将<li> {products[0].id}</li>
更改为<li> {units[0].id}</li>
。
您也可以将其别名为const {units: products} = props
,并保留代码的其余部分。
编辑
在取消回购后,我发现了几个问题。
// App.js
// Change the code to this,
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const Unit = ({ unit }) => {
const [title, setCase] = useState(unit.title)
const goUp = () => setCase(String(title).toUpperCase())
const goDown = () => setCase(String(title).toLowerCase())
return (
<div>
<span>
{unit.code} - {title}: {unit.offering}
</span>
<button onClick={goUp}>Up</button>
<button onClick={goDown}>Down</button>
</div>
)
}
const App = ({ units }) => {
return (
<div>
<ul>
{units.map(unit => (
<Unit key={unit.code} unit={unit} />
))}
</ul>
</div>
)
}
export default App
在index.js中,将其更改为:
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
const units = [
{ code: 'COMP1010', title: 'Fundamentals of Computer Science', offering: ['S1', 'S2'] },
{ code: 'COMP1750', title: 'Introduction to Business Information Systems', offering: ['S1'] },
{ code: 'COMP2110', title: 'Web Technology', offering: ['S1', 'S2'] },
{ code: 'COMP2750', title: 'Applications Modelling and Development', offering: ['S1'] },
{ code: 'MMCC2045', title: 'Interactive Web Design', offering: ['S2'] },
{ code: 'COMP3120', title: 'Advanced Web Development', offering: ['S2'] },
{ code: 'COMP3130', title: 'Mobile Application Development', offering: ['S1'] }
]
ReactDOM.render(
<React.StrictMode>
<App units={units} />
</React.StrictMode>,
document.getElementById('root')
)
serviceWorker.unregister()
发生的情况是:<App />
希望将单元传递给它,这样它就可以将其传递给<Unit />
。然而,在index.js中,您没有传递units
道具。因此,我将单位数组移动到索引中,并将其传递给它,它运行良好。
请改用const products = props.units
。