反应本机状态不更新 [英] React native state not updating
问题描述
我觉得我在这里发疯了.....我在搜索栏中输入x"但 this.setState({ filter: text });
没有更新状态.... console.log(this.state.filter);
给了我一个 '' 的值(它在构造函数中设置的初始值).我可以看到文本变量的值是 x...但它只是不更新过滤器状态.
I feel like Im going crazy here.....
I type in "x" to the searchbar but this.setState({ filter: text });
is not updating state.... console.log(this.state.filter);
gives me a value of '' (its initial value set in constructor).
I can see the value of text variable is x...but its just not updating the filter state.
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) return null;
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={(text) => {
this.setState({ filter: text });
console.log(this.state.filter);
this.searchFilterFunction();
}}
autoCorrect={false}
/>
);
};
推荐答案
状态正在更新,只是您检查和使用更新状态的方式存在缺陷.
The state is updating, it's just the way that you are checking and using the updated state is flawed.
状态是异步的,设置状态需要时间.您遇到的问题是您正在调用 setState
然后立即从状态记录值.不幸的是,当您这样做时,状态不会在您记录它时更新,因此您将获得以前的值.
State is asynchronous, it takes time for the state to set. The problem you are encountering is that you are calling setState
and then immediately logging the value from state. Unfortunately when you do this the state will not have updated by this time you log it, so you are getting the previous value.
如果要使用刚刚设置的状态值,则需要使用setState
具有的callback
函数.this.setState({key: value}, callback)
If you want to use the value of state that you have just set then you need to use the callback
function that setState
has. this.setState({key: value}, callback)
此回调允许您在设置状态后运行函数.您可以通过以下方式使用它:
This callback allows you to run functions after the state has been set. You can use it in the following way:
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
的值并且状态已更新以反映该值,它将运行 callback
,因此它会记录现在处于状态的 filter
的值,然后它会运行 searchFilterFunction
.
This means that once you set the value of filter
in the state and the state has updated to reflect that value it will then run the callback
, so it will log the value of filter
that is now in state, and then it will run the searchFilterFunction
.
你可以在 Michael Chan 的这一系列精彩文章中阅读更多关于 state 的内容
You can read more about state in this series of great articles by Michael Chan
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
这篇关于反应本机状态不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!