Answer the question
In order to leave comments, you need to log in
How to write a useState hook if the state has multiple properties?
There is a class component that needs to be converted into a functional one and the state should be converted into the useState hook. But state has several properties:
class App extends React.Component {
state = {
num: 0,
text: 'no',
textUpper: 'HELLO'
}
changeState = () => {
this.setState({
num: this.state.num + 1,
text: "yes",
textUpper: 'BYE'
});
}
render() {
return (
<div>
<button onClick={this.changeState}>like</button>
{this.state.num}
{this.state.text}
{this.state.textUpper}
</div>
);
}
}
const App = () => {
const [num, setNum] = useState(0);
const changeState = () => {
setNum(num+1);
}
return (
<div>
<button onClick={changeState}>like</button>
{num}
</div>
);
}
Answer the question
In order to leave comments, you need to log in
No matter how many variables, we use useState an infinite number of times.
const [num, setNum] = useState(0);
const [text, setText] = useState('no');
const [textUpper, setТextUpper] = useState('HELLO');
const changeState = () => {
setNum(num + 1);
setText('yes');
setТextUpper('BYE');
}
const [data, setData] = useState({
num: 0,
text: 'no',
textUpper: 'HELLO'
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question