简体   繁体   中英

State does not update using UseEffect

I have a notes state array that I have that stores the user's inputs. When a user initially opens this specific screen, the component should fetch the user's notes, and return that array or an empty one depending on if they have data or not, and display the notes on the screen if they exist. When they add a note, the component should push this new note to the notes array and call AsyncStorage.setItem to store the new array. The component should then re-render with the state variable changing.

When I run this code, though, nothing happens. My state does not seem to update, and even though I submit text, the screen does not re-render, nor does any new text appear in the section it is supposed to appear in. Anyone know where I went wrong?

UPDATE: I have added the full code block here

const [notes, setNotes] = React.useState(null);

let getNotes = async () => {
  try {
    let json = await AsyncStorage.getItem(`${id}-notes`);
    if (json != null) {
      setNotes(JSON.parse(json));
    } else {
      setNotes([]);
     }
  } catch (e) {
    console.log(e);
  }
}

React.useEffect(() => {
  console.log(notes, '- Has changed');
  getNotes();
}, [notes]);

// user input check
<TextInput 
  style={styles.text} 
  value={note} 
  onChangeText={text => {setNote(text)}}
  onSubmitEditing={event => {
    if (event.nativeEvent.text) {
      setNotes([...notes, event.nativeEvent.text]);
      AsyncStorage.setItem(`${id}-notes`, JSON.stringify(notes), (e) => {});
      setVisible(false);
     }
  }}
  multiline={true} 
  returnKeyType='go'
/>

// what i want the screen to render
{notes && notes.map(note => {
  <Note note={note} />
})}

I don't think the problem is that the state is not being set,
I think the problem is that you aren't returning anything from you map function.

Either add the return keyword.
Like this:

{notes && notes.map(note => {
  return <Note note={note} />
})}

Or simply remove the curly-brackets to turn the statement into an "implicit return".
Like this:

{notes && notes.map(note => (
  <Note note={note} />
))}

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