Hi everyone i’m recently studying react native and i have a problem. After setting the status, I cannot read the current value. My code is:
export default class HomePage extends Component {
static navigation = {}
constructor() {
super();
this.state = {
alreadyLaunched: null,
sid: "aa"
};
}
_getSid() {
console.log("state value is: ", this.state.sid);
}
_setSid() {
this.setState({
sid: "bbb"
}, function() {
console.log(this.state.sid);
})
}
componentDidMount() {
AsyncStorage.getItem("alreadyLaunched").then(value => {
if (value == null) {
AsyncStorage.setItem("alreadyLaunched", JSON.stringify(true));
this.setState({
firstLaunch: true
});
this._setSid();
} else {
this.setState({
firstLaunch: false
});
this._getSid();
}
})
}
render() {}
}
My problem is that _getSid() method print "state value is aa" and not "state value is bbb". Why?
2
Answers
Update setSid to below
Ahh setSTate is async, hence getSId prints prev value, setState has a callback func.
try this
The issue is on the
ComponentDidMount
method.Here, if
value
is null, then it updates thesid
state variable, but otherwise, it doesn’t updatesid
.When you launch this at first time, the value is null. as a result, it goes to first clause, in this case, you can see the log you’re expecting.
But after that, it always goes to second clause, and there is no chance to update the
sid
state variable