简体   繁体   中英

React State not updated in arrow function

React passing parameter with arrow function in child component

By that feedback, I can understand what is going on to update the state.

However, it seems like my code isn't working although code seems exactly same.

 constructor(props) { super(props); // this.state = { // selectedId: 0 // } this.state = { selectedId: 0 } } handleClick = (id) => { // const { name, value } = event.target; console.log(id); this.setState = ({ selectedId: id }) } render () { //const { isEditClicked } = this.state; const { selectedId } = this.state; return ( <div className='admin-match-item'> {selectedId} <CustomIconButton type='edit' id={this.props.id} handleClick={this.handleClick} /> </div> ); } }

And Child component looks below

 //Need refactoring const CustomIconButton = ({ type, id, handleClick, ...otherProps }) => ( <div> hi{id} <button className='button-icon' onClick={() => handleClick(id)}> { type == 'add' ? <AddIcon className='icon' /> : type == 'save' ? <SaveIcon className='icon'/> : type == 'edit' ? <EditIcon className='icon' /> : type == 'delete' ? <DeleteIcon className='icon' /> : <ErrorIcon className='icon' /> } </button></div> ) export default CustomIconButton;

I am passing props.id to child component and let state to be updated with the id that I am clicking. The thing is inside of console.log is returning the value I want, but it doesn't update selectedId state(always 0) Can anyone help me with this?

Change your code to this.setState({selectedId: id})

handleClick = (id) => {
  // const { name, value } = event.target;
  console.log(id);
  this.setState({selectedId: id})
}

You're doing the wrong method of setState. You have to run:

 `handleClick = (id) => {
    // const { name, value } = event.target;
    console.log(id);
    this.setState({ selectedId: id })
 }`

Don't use the equal sign (=) with the setState method. You call the setState method within your component class like so this.setState() then passing in an object with key-value pairs. That is why class component state does not change.

handleClick = (id) => {
    this.setState({
        selectedId: id
    })
}

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