hobby不是对象而是一个字符串,所以直接使用hobby访问,不用hobby.title
App.js
importReact, { Component } from‘react’ importStudentTitlefrom‘./Components/StudentTitle’ importAddStudentfrom‘./Components/AddStudent’ importStudentListfrom‘./Components/StudentList’ classAppextendsComponent { // 定义状态用于管理学员信息 state = { studentList: [ { “number”:“01”, “name”:“zce”, “age”:“40”, “sex”:“男”, “college”:“大前端”, “hobbies”: [ “篮球”, “足球” ] }, { “number”:“02”, “name”:“zoe”, “age”:“30”, “sex”:“女”, “college”:“python”, “hobbies”: [ “篮球”, “网球” ] }, { “number”:“03”, “name”:“syy”, “age”:“18”, “sex”:“男”, “college”:“大前端”, “hobbies”: [ “篮球” ] } ] } // 定义一个方法用于处理 studentList 状态 addStudent = (student, callback) => { this.setState({ studentList: […this.state.studentList, student] }, () => { callback() console.log(this.state.studentList) }) } // 定义删除操作 removeStudent = (number) => { // 核心:利用 number 找到 studentList 当中需要被删除的项,将它从原数据中拿出 // 最后再将处理后的数据重新 setState 给 state ,之后界面就会自动更新 // 01 将原数据进行深拷贝 const studentList = JSON.parse(JSON.stringify(this.state.studentList)) // 02 从拷贝后的原数据中查找 number 所对应的项 const index = studentList.findIndex(student=>student.number == number) // 03 利用上述的 index 将目标项从数组中删除 studentList.splice(index, 1) // 04 数据同步操作 //studentList:studentList 简写了 this.setState({ studentList }, () => { console.log(this.state.studentList) }) } render() { return ( <divclassName={‘container’}> <StudentTitle/> <AddStudent addStudent={this.addStudent}/> <StudentList studentList={this.state.studentList} removeStudent={this.removeStudent}/> </div> ) } } export default AppstudentList.js
importReact, { Component } from‘react’ classStudentListextendsComponent { rmStudent = (index, ev) => { ev.preventDefault() if (window.confirm(‘是否确定删除当前项’)) { this.props.removeStudent(index) } } render() { const { studentList } = this.props console.log(studentList, 2222) return ( <divclassName=“col-md-6 col-md-offset-1”> <tableclassName=“table table-striped table-hover”> <thead> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>爱好</th> <th>所属学院</th> <th>操作</th> </tr> </thead> <tbody> { studentList.map(student=> { return ( <trkey={student.number}> <td>{student.number}</td> <td>{student.name}</td> <td>{student.sex}</td> <td>{student.age}</td> <td> {student.hobbies.map((hobby, index) => { return ( <spankey={index}>{hobby}</span> ) })} </td> <td>{student.college}</td> <td> <a href=“#”onClick={(ev) => { this.rmStudent(</font><font style="color:#569cd6;background-color:#000000;">${</font><font style="color:#9cdcfe;background-color:#000000;">student</font><font style="color:#d4d4d4;background-color:#000000;">.</font><font style="color:#9cdcfe;background-color:#000000;">number</font><font style="color:#569cd6;background-color:#000000;">}</font><font style="color:#ce9178;background-color:#000000;">
, ev) }}>删除</a>
<ahref=“#”>修改</a>
</td>
</tr>
)
})
}
</tbody>
</table>
<p className=“text-center”>无学生信息</p>
<p>总共有 50 个学生</p>
<p>学生的平均年龄是 25</p>
</div>
)
}
}
export default StudentList