【问题标题】:React Native State is updating 1 keypress lateReact Native State 正在延迟更新 1 个按键
【发布时间】:2020-03-03 04:53:13
【问题描述】:

我正在为输入进行自动完成。我有一个调用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}
          />
);
}

【问题讨论】:

标签: javascript html reactjs react-native


【解决方案1】:

React Native 可以将多个 setState() 调用批处理到单个更新中以提高性能。因为 this.props 和 this.state 可能会异步更新,所以不应该依赖它们的值来计算下一个状态。

此计数器示例将无法按预期更新:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
})

首选方法是使用函数而不是对象调用 setState()。该函数将接收先前的状态作为第一个参数,并将应用更新时的道具作为第二个参数。

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}))

在您的情况下,您还应该使用函数而不是对象来设置 setState()。有时 setstate() 对象不会立即更新和渲染。

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2019-01-10
    • 2020-07-06
    • 2021-05-20
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多