开发者问题收集

TypeError:React 中的数组未定义

2020-08-09
118

我尝试使用在 React 中定义为 const 的数组,并将此数组传递到我的 App 函数中。但是,当我尝试使用它时,我收到“TypeError:products 未定义”(关于 <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;
2个回答

错误告诉您需要知道的内容。 App 上的 prop 称为 unit,但您试图从中解构 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 prop。因此,我将单位数组移至索引并将其传入,它工作正常。

Yatrix
2020-08-09

请改用 const products = props.units

Bhuwan Adhikari
2020-08-09