React setState 不会更新
React setState won't update
我正在尝试从 if 语句中设置状态,但它不会这样做。
结果我需要从 if 语句中更新状态,我可以在其中接收经度和纬度坐标,但它不会保存状态。如果我在 if 语句之外的控制台中回显,我将只读取 componentWillMount 中的第一个 setState 值。那里有什么问题?我在这里做错了什么?
所以这是结构:
componentWillMount() {
this.setState({
location: {
name: 'Riga'
}
});
}
componentDidMount() {
if (!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({
location: {
name: 'Sigulda'
}
});
});
} else {
alert('ERROR on GEOLOCATION');
}
console.log(this.state.location);
}
setState
是异步的:
this.setState({
location: {
name: 'Sigulda'
}
}, () => console.log(this.state.location));
使用setState
的回调来判断变化
setState
操作是异步的。
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.
你应该使用setState
回调函数:
this.setState({
location: {
name: 'Sigulda'
}
}, () => console.log(this.state.location));
我正在尝试从 if 语句中设置状态,但它不会这样做。 结果我需要从 if 语句中更新状态,我可以在其中接收经度和纬度坐标,但它不会保存状态。如果我在 if 语句之外的控制台中回显,我将只读取 componentWillMount 中的第一个 setState 值。那里有什么问题?我在这里做错了什么? 所以这是结构:
componentWillMount() {
this.setState({
location: {
name: 'Riga'
}
});
}
componentDidMount() {
if (!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({
location: {
name: 'Sigulda'
}
});
});
} else {
alert('ERROR on GEOLOCATION');
}
console.log(this.state.location);
}
setState
是异步的:
this.setState({
location: {
name: 'Sigulda'
}
}, () => console.log(this.state.location));
使用setState
的回调来判断变化
setState
操作是异步的。
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
你应该使用setState
回调函数:
this.setState({
location: {
name: 'Sigulda'
}
}, () => console.log(this.state.location));