React Native 我无法在第一次呼叫时更新我的状态,如何更新?

wooyq4lh  于 2023-03-09  发布在  React
关注(0)|答案(4)|浏览(132)

我无法更新我的笔记状态。当我第一次调用updateNotes函数时,它记录了空数组。但是如果我调用它两次,它就被可用的值加载了。我该如何修复这个问题?

const AddNote = ({navigation, route}) => {
  const [title, setTitle] = useState('');
  const [detail, setDetail] = useState('');
  const [notes, setNotes] = useState([]);

  function updateNotes() {
    if (title === '' || detail === '') {
      console.warn('Each input must have a value');
    }
    else {
      // setId((prev) => prev + 1);
      setNotes(prev => [...prev, {title: title, details:detail, color:color}]);
      console.log(notes);
      updateDoc(docRef, {
        notes,
      })
      .then(() => {
        console.log('UPDATED')
        navigation.navigate('Notes');
      })
    }
  }
return (...)
}

您可以在下面看到整个组件文件。

完整组件:

import { Pressable, StyleSheet, Text, View, TextInput } from 'react-native'
import { Entypo } from '@expo/vector-icons'; 
import { MaterialCommunityIcons } from '@expo/vector-icons'; 
import React, {useEffect, useState} from 'react'
// import { useSelector } from 'react-redux'
import { FontAwesome } from '@expo/vector-icons'; 

import { addDoc, serverTimestamp, doc, updateDoc } from 'firebase/firestore';
import { db, colRef } from '../firebase';
import ColorPalette from '../components/ColorPalette';

const AddNote = ({navigation, route}) => {
  const [title, setTitle] = useState('');
  const [detail, setDetail] = useState('');
  const [color, setColor] = useState('#d4ff9b');
  const [id, setId] = useState(0);
  const [notes, setNotes] = useState([]);

  // useEffect(()=>{
  //   console.log('NOTES: ',notes)
  //     updateDoc(docRef, {
  //       notes,
  //     })
  //     .then(() => {
  //       console.log('Updated');
  //       navigation.navigate('Notes');
  //     })
  // },[notes]);

  const docRef = doc(db, 'users', route.params.docId)

  async function updateNotes() {
    if (title === '' || detail === '') {
      console.warn('Each input must have a value');
    }
    else {
      setId((prev) => prev + 1);
      setNotes(prev => [...prev, {title: title, details:detail, color:color}]);
    }
  }

  const update = () => {
    updateDoc(docRef, {
      notes,
    })
    .then(() => {
      console.log('UPDATED')
      navigation.navigate('Notes');
    })
  }

  return (
    <View style={styles.noteContainer}>
        <View style={styles.titleContainer}>
          <TextInput style={styles.title} value={title} onChangeText={(text) => setTitle(text)} />
        </View>

        <View style={styles.detailsContainer}>
          <TextInput style={styles.details} value={detail} onChangeText={(text) => setDetail(text)} multiline />
        </View>

        <View style={styles.bottomContainer}>
          <View style={[styles.buttonContainer, {backgroundColor: '#00bfff'}]}>
            <Pressable android_ripple={{color: '#d9d9d9'}} onPress={update}>
              <FontAwesome style={styles.icon} name='send' size={40}/>
            </Pressable>
          </View>
          <View style={styles.buttonContainer}>
            <Pressable android_ripple={{color: '#d9d9d9'}} onPress={updateNotes}>
              <Entypo style={styles.icon} name='save' size={40}/>
            </Pressable>
          </View>
        </View>
    </View>
  )
}

我目前正在通过设置状态并使用两个不同的按钮将其更新到云来处理这个问题。

u4dcyp6a

u4dcyp6a1#

使用使用效果

useEffect(()=>{
    updateDoc(docRef, {
      notes,
    })
    .then(() => {
      console.log('UPDATED')
      navigation.navigate('Notes');
    })
},[])
lfapxunr

lfapxunr2#

我认为您需要使用useEffect来执行此操作,如下所示:

useEffect(() => {
   updateDoc(docRef, {
        notes,
      })
      .then(() => {
        console.log('UPDATED')
        navigation.navigate('Notes');
      })
}, [notes])

也可以使用另一个临时变量,如下所示:

function updateNotes() {
    if (title === '' || detail === '') {
      console.warn('Each input must have a value');
    }
    else {
      const tempNotes = [...notes, {title: title, details:detail, color:color}]
      setNotes(tempNotes);
      console.log(tempNotes);
      updateDoc(docRef, {
        tempNotes,
      })
      .then(() => {
        console.log('UPDATED')
        navigation.navigate('Notes');
      })
    }
  }
k0pti3hp

k0pti3hp3#

更新可能会有延迟。您可以尝试设置计时器,以便给予足够的时间更新useState。

function updateNotes() {
    if (title === '' || detail === '') {
      console.warn('Each input must have a value');
    } else {
      setId((prev) => prev + 1);
      // Delay the state update by 10 milliseconds
      setTimeout(() => {
        setNotes(prev => [...prev, {title: title, details: detail, color: color}]);
      }, 10);
    }
  }

或者您可以尝试将状态变量作为依赖项

useEffect(() => {
    setId((prev) => prev + 1);
    setNotes(prev => [...prev, {title: title, details: detail, color: color}]);
  }, [title, detail]);
5gfr0r5j

5gfr0r5j4#

你可能会更新你的笔记上的一些事件或useEffect(通过添加依赖数组的标题,细节。

相关问题