Ошибка React Native — useContext «не является функцией» при попытке обновить опрос с помощью пользовательского ввода

#react-native #use-context

Вопрос:

Привет, я пытаюсь добавить Usecontext, чтобы обмениваться одними и теми же данными между различными компонентами для опроса с помощью React Native.

Я получаю сообщение об ошибке: «Ошибка типа submitForm (): SetEvent не является функцией»

Вот компонент QuestionsProvider

 import React, {useState, useEffect} from 'react'; import { TextInput, View, Text, Keyboard } from 'react-native'; import { QuestionsContext } from '@/shared/contexts';    export const QuestionsProvider = ({children}) =gt; {  const [event, setEvent] = useState();  useEffect(() =gt; { console.log('the event changed ---gt;', event)  }, [event]);  return (  lt;QuestionsContext.Provider value={{...QuestionsContext, event, setEvent}}gt;  {children}   lt;/QuestionsContext.Providergt; ); }; 

А вот компонент Whathappened, в котором я использую Formik для ввода :

 import React, {useState, useEffect, useContext} from 'react'; import { TextInput, View, Text } from 'react-native'; import t from '@/locales'; import styles from '../TrainingGoingScreen.styles';  import ButtonStart from '@/shared/component/ButtonStart'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { Formik } from 'formik'; import * as yup from 'yup';   import { QuestionsProvider } from '@/shared/contexts/providers/QuestionsProvider'; import { QuestionsContext } from '@/shared/contexts';   export default function Whathappened(props) {   const [redirect, setRedirect] = useState(false);   const {event, setEvent} = useContext(QuestionsContext);   // ca ne fonctionne pas not function const {event, setEvent} = useContext(QuestionsContext);    useEffect(() =gt; {  if (redirect === true) {  props.navigation.navigate('Whatdidyouthink');  }  }, [redirect]);   const nextPage = async (values) =gt; {  setEvent(values)  console.log('event ---gt; ', event)   };   return (  lt;QuestionsProvidergt;  lt;KeyboardAwareScrollView contentContainerStyle={{minHeight:'100%'}}gt;  lt;Formik  onSubmit={(values) =gt; nextPage(values)}  initialValues={{  happened: '',  }}  style={{ flex: 1 }}  validationSchema={yup.object().shape({  happened: yup.string().required(),  })}gt;  {({  values,  handleChange,  errors,  setFieldTouched,  touched,  handleSubmit,  }) =gt; (  lt;View style={styles.container}gt;  lt;Viewgt;  lt;Text style={styles.centeredtitle}gt;  {t('training.goingon.whathappened')}  lt;/Textgt;  lt;Text style={styles.description}gt;  {t('training.goingon.question')}  {' 1 '}  {t('training.goingon.ofnumber')}  lt;/Textgt;  {/* User input */}  lt;TextInput  placeholder={t('training.goingon.inputanswer')}  value={values.happened}  placeholderTextColor="grey"  onChangeText={handleChange('happened')}  onBlur={() =gt; setFieldTouched('happened')}  style={styles.input}  autoCapitalize="none"  keyboardType="default"  textContentType="name"  returnKeyType="next"  /gt;  {touched.happened amp;amp; errors.happened amp;amp; (  lt;Text style={styles.errorMsg}gt;  {t('training.goingon.inputanswer')}  lt;/Textgt;  )}  lt;/Viewgt;  lt;View style={styles.bottom}gt;  lt;ButtonStart  onPress={handleSubmit}  buttonText={t('training.goingon.nexquestionbutton')}  showRightArrow={true}  /gt;  lt;/Viewgt;  lt;/Viewgt;  )}  lt;/Formikgt;  lt;/KeyboardAwareScrollViewgt;    lt;/QuestionsProvidergt;  ); } 

Ответ №1:

Я, наконец, использовал редуктор приложений, чтобы решить эту проблему:

 const [state, dispatch] = React.useReducer(  (prevState, action) =gt; {  switch (action.type) {  case 'SET_BEHAVIOUR':  return {  ...prevState,  behaviour: action.behaviour,  }; }