简体   繁体   中英

React Native - State doesn't change correctly on button press (TouchableHighlight)

i want to change a state after a button press on a touchableHighlight component. The problem is that the state doesn't update immediately, but it does after i press another one of the rendered components, and it adds the previous letter to the state. This is the code:

export default function App() {

  const [word, setword] = useState('');
  const handleChange=(e) => {
    setword(word.concat(e.target.outerText));
  };

  return (
    <View style={styles.container}>
      <View style={styles.row}>
      {wordpuzzle.square[0].map((letter, index) => {
        return(
          <TouchableHighlight style={styles.touchableHighlight} key={index} onPress={handleChange}>
            <View style={styles.button}>
              <Text style={styles.text}>{letter}</Text>
            </View>
          </TouchableHighlight>
        )})
      } 

This is the wordpuzzle.json file from where I'm mapping stuff to render inside components.

{
    "square": [
        ["P", "E", "R", "E"],
        ["I", "U", "B", "A"],
        ["T", "A", "B", "L"],
        ["E", "H", "C", "I"]
    ],
    "10": ["pubblicati"],
    "9": ["pubbliche", "pubblicai"],
    "8": ["pubblica"],
    "7": ["pubiche", "barbuta", "barbuti", "barbute"],
    "6": ["pubica", "rubati", "rubate"],
    "5": ["barbe", "beare"],
    "4": ["pere", "pera", "erba", "bali", "pube", "pubi", "bare",
        "taci", "aura", "aure", "ruba"
    ],
    "3": ["eta", "pia", "pie", "che", "ali", "bea"]
}

Might try using previous value in setting state based on previous state

setword(prev => prev.concat(e.target.outerText));

Please try it!

setword([...word.concat(e.target.outerText)]);

Word state is char array. when you call setWord, word content would be added but word variable address itself doesn't change, the system doesn't recognize state changing so UI component doesn't refresh. Basically you should call setWord with a new array.

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