React native 反应本机状态不更新
我觉得我快疯了。。。。。 我在搜索栏中键入“x”,但React native 反应本机状态不更新,react-native,React Native,我觉得我快疯了。。。。。 我在搜索栏中键入“x”,但this.setState({filter:text})未更新状态控制台.log(this.state.filter)给我一个值“”(它的初始值在构造函数中设置)。 我可以看到文本变量的值是x…但它只是不更新过滤器状态 constructor(props) { super(props); this.state = { timer: 30 * 60, lat: 0, lng: 0,
this.setState({filter:text})代码>未更新状态<代码>控制台.log(this.state.filter)代码>给我一个值“”(它的初始值在构造函数中设置)。
我可以看到文本变量的值是x…但它只是不更新过滤器状态
constructor(props) {
super(props);
this.state = {
timer: 30 * 60,
lat: 0,
lng: 0,
loading: false,
data: [],
pagetoken: null,
refreshing: false,
waiting4answer: false,
placeName: null,
placeUri: null,
filter: '',
};
}
renderHeader=()=>{
if(this.state.waiting4answer==false)返回null;
返回(
{
this.setState({filter:text});
console.log(this.state.filter);
this.searchFilterFunction();
}}
自动更正={false}
/>
);
};
状态正在更新,只是您检查和使用更新状态的方式有缺陷
状态是异步的
状态是异步的,设置状态需要时间。您遇到的问题是调用setState
,然后立即从state记录值。不幸的是,当您这样做时,状态在您记录它的时候还没有更新,所以您得到的是以前的值
State接受回调
如果要使用刚刚设置的状态值,则需要使用setState
具有的callback
函数this.setState({key:value},回调)
此回调允许您在设置状态后运行函数。您可以通过以下方式使用它:
this.setState({filter: text}, () => {
// put the things you wish to occur after you have set your state.
console.log(this.state.filter);
// I am guessing your searchFilterFunction requires the updated filter value in state
// so put that here too
this.searchFilterFunction();
});
这意味着,一旦您在状态中设置了filter
的值,并且状态已更新以反映该值,它将运行回调
,因此它将记录当前处于状态的filter
的值,然后运行搜索过滤器功能
进一步阅读
你可以在MichaelChan的这一系列优秀文章中阅读更多关于州的信息
设置更新状态后,立即使用setState回调获取更新状态
this.setState({ filter: text }, () => {
console.log(this.state.filter);
});
反应设置状态为设置状态
为。使用Text
组件显示值我们可以知道预期输出吗?使用setstate后,状态不会立即更新。
this.setState({ filter: text }, () => {
console.log(this.state.filter);
});