猿问

从父组件向子组件发送两次道具

当我将道具作为单独的组件发送两次时,我的地图未定义


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.js


import 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>

        )

    }

}


翻过高山走不出你
浏览 108回答 2
2回答

慕尼黑8549860

组件的使用都会创建单独的实例。只有您在该实例中提供的道具才能作为 this.props 使用。在<Todo todo = {this.state.todos} />只有待办事项道具可用,deletTodo不可用。在{ <Todo deletTodo = {this.deletTodo}/> }只有deletTodo可用,待办事项道具不可用。这就是您将收到错误的原因Cannot read property 'map' of undefined。您可以通过提供一个默认道具来解决这个问题,这样就没有任何道具是未定义的。Todo.defaultProps = {&nbsp; todo: [],&nbsp; deletTodo: () => null,}

富国沪深

在构造函数中设置您的状态constructor() {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; &nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//set state here&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答