简体   繁体   English

State 不使用 UseEffect 更新

[英]State does not update using UseEffect

I have a notes state array that I have that stores the user's inputs.我有一个存储用户输入的notes state 数组。 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.当他们添加注释时,组件应将此新注释推送到notes数组并调用AsyncStorage.setItem来存储新数组。 The component should then re-render with the state variable changing.然后该组件应该随着 state 变量的变化而重新渲染。

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?我的 state 似乎没有更新,即使我提交了文本,屏幕也没有重新渲染,也没有任何新文本出现在它应该出现的部分。有人知道我哪里出错了吗?

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,我不认为问题是没有设置 state,
I think the problem is that you aren't returning anything from you map function.我认为问题在于您没有从map function 那里返回任何东西。

Either add the return keyword.添加return关键字。
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} />
))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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