我在訪問陣列元素時未定義,但僅在使用陣列名稱時控制臺顯示值。編碼:
const Part = (props) => {
return <p>{props.name} {props.exercises}</p>
}
const Content = (props) => {
// when i use console.log(props[0])
// it shows undefined
//
// but when i use console.log(props)
// it shows the array information as
// {parts: Array(3)}
// parts: Array(3)
// 0: {name: 'Fundamentals of React', exercises: 10}
// 1: {name: 'Using props to pass data', exercises: 7}
// 2: {name: 'State of a component', exercises: 14}
// length: 3
// [[Prototype]]: Array(0)
// [[Prototype]]: Object
return (
<div>
<Part parts={props[0]} />
</div>
)
}
const App = () => {
const course = 'Half Stack application development'
const parts = [
{
name: 'Fundamentals of React',
exercises: 10
},
{
name: 'Using props to pass data',
exercises: 7
},
{
name: 'State of a component',
exercises: 14
}
]
return (
<div>
<Content parts={parts} />
</div>
)
}
所以我不明白為什么在 Content 中,console.log(props)回傳陣列資訊但console.log(props[0])說未定義,在 App 中什么也得不到。
更新:謝謝大家的回復。現在我知道如果我在 Content 中使用 'props.parts',我會得到正確的結果。然后我又遇到了另一個問題(對不起,我是 JS 和 React 的新手):因為“parts”是在 App 中定義的并傳遞給 Content。在定義內容時,我不應該使用或知道“部分”。那么為什么我需要在 Content 中使用“props.parts”呢?
uj5u.com熱心網友回復:
// when i use console.log(props[0])
// it shows undefined
因為陣列變數名稱parts正如您在此處提到的:
// but when i use console.log(props)
// it shows the array information as
// {parts: Array(3)}
// parts: Array(3)
所以試試這個:
console.log(props.parts)
或者
console.log(props.parts[0])
uj5u.com熱心網友回復:
console.log(props) 不回傳陣列,它回傳物件有 1 個屬性名稱部分(部分是陣列)
=> 解決方案:
const Content = props => {
const { parts } = props;
return (
<div>
<Part parts=parts[0] />
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344942.html
標籤:javascript 数组 反应
上一篇:將函陣列件轉換為類組件
