[英]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.我将 props.id 传递给子组件,并让 state 更新为我点击的 id。 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?
console.log 里面的东西正在返回我想要的值,但它不会更新 selectedId 状态(始终为 0) 任何人都可以帮助我吗?
Change your code to this.setState({selectedId: id})
将您的代码更改为
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.您正在执行错误的 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.不要在
setState
方法中使用等号 (=) 。 You call the setState
method within your component class like so this.setState()
then passing in an object with key-value pairs.你在组件类中调用
setState
方法,像这样this.setState()
然后传入一个带有键值对的对象。 That is why class component state does not change.这就是类组件状态不会改变的原因。
handleClick = (id) => {
this.setState({
selectedId: id
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.