简体   繁体   中英

'key' is not defined no-undef setState ReactJS

export default class Home extends Component {  
 state  = {
        items : [ { text: 'Buy grocery', done: true},
{ text: 'Play guitar', done: false},
{ text: 'Romantic dinner', done: false}
]
}
onItemClick  = () =>{ 
 this.setState(    
    prevState => ({
        items: prevState.items.map(
      el => el.key === key? { ...el, done: true }: el
        )

      })
  )
}
    render() {
        return (
            <Fragment>
            <h1>
                Home Page
            </h1>
            <TodoList items={this.state.items} clickAction={this.onItemClick} />
            </Fragment>
        )
    }
export default class TodoList extends Component {

    render() {
       const itemlist = this.props.items.map((item, index) =>{
        return <div key={index}>  
        <h4 onClick={this.props.clickAction}>  {item.text + " " + item.done}</h4>  </div>
     })
        return (
            <Fragment>
            <h5>
            TodoList Page
            </h5>
            <section>
            {itemlist}
        </section>
        </Fragment>
        )
    }

}

I want to update a single object property inside the array. onItemClick function, which should be called when user clicks an item in the list, if the item is marked "false" as done. Otherwise the onItemClick should not be called and the click event itself should not be propagated further. getting error 'key' is not defined no-undef

When you are doing this:

  el => el.key === key? { ...el, done: true }: el

you comapre el.key to key but the variable key is never defined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM