TypeError:未定义不是一个对象在React Native中评估'addTodo

我收到异常 TypeError: undefined is not an object (evaluating 'addTodo(title, description).then') 该函数工作正常并且状态更新正常,但它没有按预期工作。


添加Todo.js:


import { useNavigation } from '@react-navigation/native';

import React , {useContext, useState} from 'react';

import { View } from 'react-native';

import { Input , Button} from 'react-native-elements';

import { TextInput } from 'react-native-gesture-handler';

import {cardContext} from '../contextApi/cardContext';



const NewTodoInput = () =>{

const { addTodo } = useContext(cardContext);

const navigation = useNavigation();



const [title , setTitle] = useState()

const [description , setDescription] = useState()

const handleOnSubmit = ()=>{

    

    addTodo(title,description)

    .then((data)=>{

        navigation.navigate('TodoApp');

        console.log('Added Succesfully : ' + data);

    })

    .catch((e)=>{console.log(e)});


}

return (

    <View>

    <Input 

    placeholder = 'Title'

    onChangeText= {(val)=>{setTitle(val)}}

    />

    <Input 

    placeholder = 'Your todo'

    multiline = {true}

    onChangeText = {(val) => {setDescription(val)}}

    />

    <Button 

        buttonStyle= {{backgroundColor : 'black'}}

        title = 'Submit'

        onPress = {handleOnSubmit}

        

        

    />

    </View>


)


}


export default NewTodoInput ;

上下文.js


import React , {createContext, useState} from 'react'


export const cardContext = createContext();


const Data = (props) =>{

    const [data , setData] = useState(

        //todo Add id to the data

        [

            {title : 'This is title 1' , Description : 'this is description 1'},

            {title : 'This is title 2' , Description : 'this is description 2'},

            {title : 'This is title 3' , Description : 'this is description 3'},

            {title : 'This is title 4' , Description : 'this is description 4'},

        ]

        

    ) 




潇湘沐
浏览 102回答 1
1回答

慕妹3242003

如果您想更改 addTodo 以使其返回评论中所述的承诺,那么这里是:const addTodo = (title , description) =>{&nbsp; &nbsp;setData( [...data , {title : title, Description : description}] )&nbsp; &nbsp;return new Promise((resolve, reject) => {&nbsp; &nbsp; &nbsp; &nbsp;resolve("data") // Do something here preferable what you need inside .then()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript