简体   繁体   中英

React Native State is updating 1 keypress late

I am making an autocomplete for an input. I have an input which calls the queryText function onChangeText . The queryText recieves a string and an array, it makes a new array with strings that match the passed string and updates state. The issue is my state is updated late. In the code below if I type the letter "w" I get back the entire poi array instead of just walmart. But if I type "b" after I get only walmart (I should get nothing). If I erase "b" I get an empty array (I should get walmart). It seems like my autocomplete state is 1 keypress behind.

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 may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

This counter example will fail to update as expected:

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

The preferred approach is to call setState() with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.

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

in your case, you should also make setState() with function instead of object. sometimes setstate() object is not immediately update and render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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