繁体   English   中英

React Native State 晚更新 1 个按键

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM