When I try to learn the functional component of react, I'm try to change the class component to the functional component. But my code is not right, I need so help.
I change code from the below project. (https://github.com/ahfarmer/calculator/blob/37b56077e78b82bf2088ec993d55becb47538de9/src/component/App.js)
https://github.com/ahfarmer/calculator
import { useState, Component } from "react";
import { Display } from "./Display";
import { ButtonPanel } from "./ButtonPanel";
import calculate from "../logic/calculate";
import "./App.css";
function App2() {
const [state, setState] = useState({
total: null,
next: null,
operation: null,
});
const handleClick = (buttonName) => {
let newValue = calculate({total: state.total, next: state.next, operation: state.operation}, buttonName);
console.log(newValue);
setState(newValue);
};
return (
<div className="component-app">
<Display value={state.next || state.total || "0"} />
<ButtonPanel clickHandler={handleClick} />
</div>
);
}
class App extends Component {
state = {
total: null,
next: null,
operation: null,
};
handleClick = (buttonName) => {
let newValue = calculate(this.state, buttonName);
console.log(newValue);
this.setState(newValue);
};
render() {
return (
<div className="component-app">
<Display value={this.state.next || this.state.total || "0"} />
<ButtonPanel clickHandler={this.handleClick} />
</div>
);
}
}
// App is fine
export default App;
// App is not fine
// export default App2;
same step, but result is different.
App 2 is {}
App2 Log
tap 1
{
"next": "1",
"total": null
}
tap +
{
"total": "1",
"next": null,
"operation": "+"
}
tap 2
{
"next": "2"
}
tap =
{}
App Log
tap 1
{
"next": "1",
"total": null
}
tap +
{
"total": "1",
"next": null,
"operation": "+"
}
tap 2
{
"next": "2"
}
tap =
{
"total": "3",
"next": null,
"operation": null
}
=, the result is diff. Do you know why? I think the problem might be thesetState()in App2. I don't know how to fix.