if i'm using state object within functional component like this:
const state = {
stage: useState(1),
players: useState([]),
result: useState(""),
};
then how would i be able to define the setState function and use it ? thanks in advance
CodePudding user response:
Those are three completely separate and unique states, and they must be set individually.
useState
returns an array with two items. The first item is the states value, and the second item is a function used to set that state.
So with this state
object, you would get the state value with:
state.stage[0] // get "stage" value
And set the state with:
state.stage[1](newStage) // set "stage" value
But that's not how react applications are typically structured because trying to remember if you should use [0]
or [1]
is pretty ugly.
Instead, this is typically laid out like this:
const [stage, setStage] = useState(1),
const [players, setPlayers] = useState([])
const [result, setResult] = useState("")
And now reading state is as easy as stage
and setting it as easy as setStage(newStage)
.
CodePudding user response:
I'd prefer having a single state object, with 3 properties, using a single useState
call.
let [game,updateGame] = useState({stage: 1, players: [], result: ''});
I'd hesitate using the state
as a variable name, as it may be confusing, when another developer looks at the code for the 1st time.
You can update it as follows:
function goToNextLevel() {
updateGame(game=> {
if(game.stage == 12) {
return {...game, result: 'win'};
} else {
return {...game, stage: game.stage 1};
}
});
}