I'm trying to display count per click using the button but I ran into a problem with my code. When I run my code, it fails to compile, but when you inspect the page you can see the time being displayed. Here's my code.
import React from 'react'
export default class Profile extends React.Component{
constructor(){
super();
this.state={
name:'Abdur Rehman',
email: '[email protected]',
count: 0,
}
}
test(){
this.setState({
name: 'Jamal',
email: '[email protected]',
count: count 1
}
)
}
render(){
return(
<div>
<h1>hello {this.state.name}</h1>
<h1>Email: {this.state.email}</h1>
<h1>Count: {this.state.count}</h1>
<button onClick={()=>{this.test()}}>Update Name</button>
</div>
);
}
}
CodePudding user response:
import previous state, also dont mutate the this.state
variable outside of the constructor
function, use this.setState
in the test function, this will also rerender the component
import React from 'react'
export default class Profile extends React.Component{
constructor(){
super();
this.state={
name:'Abdur Rehman',
email: '[email protected]',
count: 0,
}
}
test(){
this.setState({
...this.state,
name: 'Jamal',
email: '[email protected]',
count: this.state.count 1
}
)
}
render(){
return(
<div>
<h1>hello {this.state.name}</h1>
<h1>Email: {this.state.email}</h1>
<h1>Count: {this.state.count}</h1>
<button onClick={()=>{this.test()}}>Update Name</button>
</div>
);
}
}
CodePudding user response:
I'm not sure why it would fail to compile but I can spot a logic error in your test method.
count: count 1
should be:
count: this.state.count 1
or better yet:
count: this.state.count
This is because you need to remember to reference the instance of the class Profile using the "this" keyword. This is necessary because any assignment needs to reference the explicit path the count variable is stored at, i.e this.state.count.
see if this does anything for you :)