我有一个包含数组数组的对象。我能够让它按照我想要的方式呈现。然而,React 键给我带来了麻烦;抛出此“警告:列表中的每个子项都应该有一个唯一的“key”道具。”
我尝试在原始数组对象中为每个数组中的每个元素提供唯一的“id”属性,但没有帮助。
我也浏览了这些,但我想我有所有的建议:在reactjs中,数组或迭代器中的每个子元素都应该有一个唯一的“key”属性 https://stackoverflow.com/questions/42074812/each-child-in-an-array-or-iterator-should-have-a-unique-key-prop-in-reactjs?rq=1
警告:列表中的每个子项都应该有一个唯一的“key”道具 https://stackoverflow.com/questions/55153873/warning-each-child-in-a-list-should-have-a-unique-key-prop?rq=1
警告:数组或迭代器中的每个子项都应该有一个唯一的“key”属性。检查`ListView`的渲染方法 https://stackoverflow.com/questions/34576332/warning-each-child-in-an-array-or-iterator-should-have-a-unique-key-prop-che?rq=1
我的对象
const courses =
[
{
name: 'Half Stack application development',
id: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 'Fundamentals of React'
},
{
name: 'Using props to pass data',
exercises: 7,
id: 'Using props to pass data'
},
{
name: 'State of a component',
exercises: 14,
id: 'State of a component'
},
{
name: 'Redux',
exercises: 11,
id: 'Redux'
}
]
},
{
name: 'Node.js',
id: 'Node.js',
parts: [
{
name: 'Routing',
exercises: 3,
id: 'Routing'
},
{
name: 'Middlewares',
exercises: 7,
id: 'Middlewares'
}
]
}
]
ReactDOM.render(<App course={courses}/>, document.getElementById('root'));
这是回调顺序:
应用程序 -> 课程 -> 课程 -> {标题、内容 -> 部分}
const App = ({course}) => {
return (
<>
<Courses course={course} />
</>
)
}
const Courses = ({course}) => {
console.log("Starting.....")
const courseList = course.map(nameConent => nameConent)
// console.log(courseList)
// const idList = courseList.map(eachCourse =>eachCourse.id)
const mapEverything = () => courseList.map(a => <Course name={a.name} partsList={a.parts} id={a.id}/>)
// const mapEverything = () => courseList.map(a => console.log(a.id))
// console.log("CourseID",idList)
return (
<>
{mapEverything()}
</>
)
}
const Course = ({name,partsList,id}) => {
// console.log(name)
console.log("CourseID", id)
return (
<>
<div key={id}>
<Header header={name} id={id}/>
<Content contents={partsList} id={id+"======"}/>
</div>
</>
)
}
const Content = ({contents,id}) => {
console.log("contentsID",id)
const partList = () => contents.map(part =>
<Part
name={part.name}
id={part.id}
exercises={part.exercises}
/>
)
const getSumofArray = (accumulator, currentValue) => accumulator + currentValue
const exeList = contents.map(content => content.exercises).reduce(getSumofArray)
// console.log(exeList)
return (
<>
<ul key={id}>
{partList()}
</ul>
<b>total exercises: {exeList}</b>
</>
)
}
const Header = ({header, id}) => {
console.log("HeaderID", id)
return (
<>
<h1 key={id}>
{header}
</h1>
</>
)
}
const Part = ({name, id, exercises}) => {
console.log("PartID", id)
return (
<>
<li key={id}>
{name}: {exercises}
</li>
</>
)
}
课程和内容组件遇到问题。
警告截图:https://drive.google.com/open?id=1kcLlF0d90BG6LXPojDtfSlBFGafC9HC_ https://drive.google.com/open?id=1kcLlF0d90BG6LXPojDtfSlBFGafC9HC_