Ошибка типа: неопределенный не является объектом (вычисление ‘addTodo (заголовок, описание).затем’) в React Native

#javascript #reactjs #react-native #react-native-navigation #context-api

#javascript #reactjs #react-native #react-native-навигация #реагировать-контекст

Вопрос:

Я получаю исключение TypeError: неопределенный не является объектом (вычисление ‘addTodo (заголовок, описание).).затем’) функция работала нормально, и состояния обновляются нормально, но работают не так, как ожидалось.

AddTodo.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 ;
  

Context.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'},



        ]
        
    ) 
    // Addd id to the data
    const addTodo = (title , description) =>{
            
            setData( [...data , {title : title, Description : description}] )
    }
    const removeTodo = (id) => {
        setData(data.filter(data => data.id != id))

    }
    return (
        <cardContext.Provider value= {{data , addTodo}} >
        {props.children}
        </cardContext.Provider>

    )
}
export default Data;
  

И я получаю следующую ошибку :

 TypeError: undefined is not an object (evaluating 'addTodo(title, description).then')
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:148:8 in registerError
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:59:8 in errorImpl
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:33:4 in console.error
- node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
- node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
- node_modulesreact-nativeLibrariesCoreExceptionsManager.js:171:19 in handleException
- node_modulesreact-nativeLibrariesCoresetUpErrorHandling.js:24:6 in handleError
- node_modulesexpo-error-recoverybuildErrorRecovery.fx.js:9:32 in ErrorUtils.setGlobalHandler$argument_0
- node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
- node_modulesregenerator-runtimeruntime.js:293:29 in invoke
- node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
- node_modulesregenerator-runtimeruntime.js:154:27 in invoke
- node_modulesregenerator-runtimeruntime.js:164:18 in PromiseImpl.resolve.then$argument_0
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:130:14 in _callTimer
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:181:14 in _callImmediatesPass
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:441:30 in callImmediates
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:387:6 in __callImmediates
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:135:6 in __guard$argument_0
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:134:4 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

TypeError: undefined is not an object (evaluating 'addTodo(title, description).then')
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:148:8 in registerError
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:59:8 in errorImpl
- node_modulesreact-nativeLibrariesLogBoxLogBox.js:33:4 in console.error
- node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
- node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
- node_modulesreact-nativeLibrariesCoreExceptionsManager.js:171:19 in handleException
- node_modulesreact-nativeLibrariesCoresetUpErrorHandling.js:24:6 in handleError
- node_modulesexpo-error-recoverybuildErrorRecovery.fx.js:9:32 in ErrorUtils.setGlobalHandler$argument_0
- node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
- node_modulesregenerator-runtimeruntime.js:293:29 in invoke
- node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
- node_modulesregenerator-runtimeruntime.js:154:27 in invoke
- node_modulesregenerator-runtimeruntime.js:164:18 in PromiseImpl.resolve.then$argument_0
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:130:14 in _callTimer
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:181:14 in _callImmediatesPass
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:441:30 in callImmediates
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:387:6 in __callImmediates
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:135:6 in __guard$argument_0
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:134:4 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue
  

P.S: — handleonSubmit работал нормально, пока я не добавил к нему метод then и catch. Прямо сейчас я получаю сообщение об ошибке, но мои состояния все еще добавляются.

Комментарии:

1. addTodo не возвращает a Promise , поэтому у вас нет .then() in handleOnSubmit() .

2. @norbitrial как можно изменить addTodo , чтобы он возвращал обещание.

Ответ №1:

Если вы хотите изменить addTodo таким образом, чтобы он возвращал обещание, указанное в комментарии, то вот оно:

 const addTodo = (title , description) =>{
   setData( [...data , {title : title, Description : description}] )
   return new Promise((resolve, reject) => {
       resolve("data") // Do something here preferable what you need inside .then()
                      })
}