当我将道具作为单独的组件发送两次时,我的地图未定义import React, { Component } from 'react'import Todo from './Todo';export default class App extends Component { state = { todos: [ {id : 1 , content: "lets sleep"}, {id: 2, content:"lets eat "} ]} deletTodo = (id) => { console.log(id)} render() { return ( <div className="App container"> <h1 className="center blue-text">Todo's</h1> <Todo todo = {this.state.todos} /> { <Todo deletTodo = {this.deletTodo}/> } </div> ) }}它向我抛出未定义的地图,但以下代码可以解决问题,我不知道为什么有人解释 <Todo todo = {this.state.todos} deletTodo= {this.deletTodo}/>以下是我获取道具的 Todo.jsimport React, { Component } from 'react'export default class Todo extends Component { render() { return ( <div className= "todos collection"> { this.props.todo.map((td)=>{ return ( <div className="collection-item" key ={td.id} > <span>{td.content}</span> </div> )})} </div> ) }}
2 回答

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
组件的使用都会创建单独的实例。只有您在该实例中提供的道具才能作为 this.props 使用。
在<Todo todo = {this.state.todos} />只有待办事项道具可用,deletTodo不可用。在{ <Todo deletTodo = {this.deletTodo}/> }只有deletTodo可用,待办事项道具不可用。这就是您将收到错误的原因Cannot read property 'map' of undefined。您可以通过提供一个默认道具来解决这个问题,这样就没有任何道具是未定义的。
Todo.defaultProps = {
todo: [],
deletTodo: () => null,
}
添加回答
举报
0/150
提交
取消