[英]React Native State is updating 1 keypress late
我正在為輸入做一個自動完成。 我有一個調用queryText
函數onChangeText
的輸入。 queryText
接收一個字符串和一個數組,它使用與傳遞的字符串匹配的字符串創建一個新數組並更新狀態。 問題是我的狀態更新晚了。 在下面的代碼中,如果我輸入字母“w”,我會返回整個 poi 數組,而不僅僅是 walmart。 但是,如果我在只得到 walmart 之后輸入“b”(我什么也得不到)。 如果我擦除“b”,我會得到一個空數組(我應該得到 walmart)。 似乎我的自動完成狀態落后 1 個按鍵。
export default function IndoorForm() {
const poi = ["test1", "test2", "test3", "walmart"]
const [value, onChangeText] = React.useState('');
const [autocomplete, setAutocomplete] = React.useState([...poi]);
const [query, setQuery] = React.useState('');
const queryText = (text, poi) => {
let sanitizedText = text.toLowerCase();
const queryResult = poi.filter(location => location.includes(sanitizedText) !== false);
setAutocomplete([...queryResult]);
onChangeText(text);
console.log("-----New Text----")
console.log(queryResult); //this is displaying the correct array
console.log(text);
console.log(autocomplete); //this value is 1 behind what is expected
}
return (
<TextInput
key={autocomplete}
style={styles.input}
onChangeText={text => queryText(text, poi)}
value={value}
/>
);
}
React Native 可以將多個 setState() 調用批處理為單個更新以提高性能。 因為 this.props 和 this.state 可能會異步更新,所以你不應該依賴它們的值來計算下一個狀態。
此反例將無法按預期更新:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
})
首選方法是使用函數而不是對象調用 setState()。 該函數將接收先前的狀態作為第一個參數,並將應用更新時的 props 作為第二個參數。
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}))
在您的情況下,您還應該使用函數而不是對象來創建 setState()。 有時 setstate() 對象不會立即更新和呈現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.