簡體   English   中英

數組類型狀態的setState如何推送數據?

[英]How to push data in the setState of array-type state?

我有一個狀態data 我想推送表單的新條目

{  task:'ANy task',key:Math.random().toString() }

使用 setData 時在數據數組中。

我嘗試了這里提到的許多方法,但不知道為什么它不起作用。

這是我的代碼。

import React, { useState } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import { StatusBar } from "expo-status-bar";

const Addtask = ({navigation}) => {
 
  const [data,setData] = useState([]);

  console.log("from add = ",data)

  const [task, setTask] = useState("");


  const handleSubmit = () => {
    console.log("submit pressed for task = ", task)
    

    const updatedData = [...data,{
      task:task,
      key: Math.random().toString(),
    }]
    //here i am setting the data
    setData(prevState => [...prevState,updatedData]);
    console.log("data after adding task",data)
    
    navigation.navigate("Tasklist",{data:data})
  }

  return (
    <View style={styles.container}>
      <StatusBar style="light" backgroundColor="midnightblue" />
      <View>
        <Text style={styles.text}>Add Task Here</Text>
      </View>

      <View>
        <TextInput
          style={styles.input}
          onChangeText={setTask}
          value={task}
          onChange={setTask}
          placeholder="Type your task"
          keyboardType="ascii-capable"
        />
      </View>

      <View style={styles.buttoms}>
        <View style={{margin:4}}>
          <Button color={'red'} onPress={()=>{navigation.goBack()}} title="Cancel"></Button>
        </View>
        <View style={{margin:4}}>
          <Button color={'lightblue'} onPress={()=>setTask('')} title="Clear"></Button>
        </View>
        <View style={{margin:4}}>
          <Button color={'green'} onPress={handleSubmit} title="Save"></Button>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  .
  .
  .
});
export default Addtask;

為了調試,我使用了控制台 stmts,它顯示task值正確地進入了handleSubmit()但它沒有被推送。

日志

submit pressed for task =  Morning bike ride.
data after adding task Array []

因為你已經擁有

const updatedData = [...data,{
  task:task,
  key: Math.random().toString(),
}]

你不需要setData(prevState => [...prevState,updatedData])你可以像setData(updatedData)一樣將updatedData分配給setData

您可以使用

setData(current => [...current, {
  task:task,
  key: Math.random().toString(),
}])

那么你不需要updatedData

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM