简体   繁体   English

如果导航到 React Native 中的其他屏幕,如何保留 formik 表单值

[英]How to persist formik form values if navigate to other screen in React Native

I am working on app where I am using formik form, it working fine but I face one issue when I open camera and take a picture when get back the form filled lost .我正在开发使用 formik 表单的应用程序,它运行良好,但是当我打开相机并在找回填写的表单时拍照时遇到了一个问题。 I want to keep all values persist if I open camera etc .如果我打开相机等,我想保持所有值。 I really tried hard but didn't find any solution .我真的很努力,但没有找到任何解决方案。 Could someone please help me how to resolve this issue.有人可以帮我解决这个问题。

Thanks谢谢

    <Form
      initialValues={{ username: "", email: '' }}
      onSubmit={handleSubmit}
      key={Math.random()}
    >
    
      <FormField
        autoCapitalize="none"
        autoCorrect={false}
        icon="account"
        keyboardType="email-address"
        name="username"
        placeholder="Username"
        textContentType="emailAddress"
        maxLength={20}
        style={{ width: "100%" }}
      />
    
      <ListItemSeparator />
    
      <View style={{ marginVertical: 20 }}>
        <>
          <MaterialCommunityIcons name="camera" size={40} color="#666" onPress={() => cameraToggle(true)} />
    
          <Image resizeMode="cover" source={{ uri: camerBinaryImage && camerBinaryImage.uri }} style={{ height: Object.keys(camerBinaryImage).length > 0 ? 300 : 0, width: Object.keys(camerBinaryImage).length > 0 ? 300 : 0 }} />
        </>
      </View>
    
    
      <ListItemSeparator />
      <AppText style={styles.slugTitle}>Email</AppText>
    
      <ListItemSeparator />
      <FormField
        autoCapitalize="none"
        autoCorrect={false}
        keyboardType="email-address"
        comment={true}
        name="email"
        placeholder="Email"
        textContentType="emailAddress"
        style={{ width: "100%" }}
      />
    
    </Form>

If you can imagine it, you can program it.如果你能想象它,你就可以编程。 Maybe this will help you friend.也许这会帮助你的朋友。

You must first install asynstorage .您必须先安装asyncstorage Now create a hook called useAsyncStorage.js and add the following code现在创建一个名为useAsyncStorage.js的钩子并添加以下代码

 /* Librarys*/ import AsyncStorage from '@react-native-async-storage/async-storage'; const storeData = async (key, value) => { try { return await AsyncStorage.setItem(key, value); } catch (error) { console.log(error) } }, getData = async (key) => { try { let data = await AsyncStorage.getItem(key); return key !== null ? data : null; } catch (error) { console.log(error) } }, /* JSON */ storeDataJson = async (key, value) => { try { const jsonValue = JSON.stringify(value) await AsyncStorage.setItem(key, jsonValue) } catch (err) { console.log(err); } }, getDataJson = async key => { try { const jsonValue = await AsyncStorage.getItem(key); return jsonValue !== null ? JSON.parse(jsonValue) : null; } catch (err) { console.log(err); } } module.exports = { storeData, getData, storeDataJson, getDataJson }

Now an example to be able to use asynstorage with formik现在是一个能够将 asyncstorage 与 formik 一起使用的示例

 import React, { useEffect } from 'react'; import { TextInput } from 'react-native'; import { Formik, useFormik } from 'formik'; /* AsyncStorage */ import { storeData, getData } from './useAsyncStorage'; // your path const CustomComponent = () => { const initialValues = useFormik({ initialValues: { name: 'Husdady' } }) useEffect(() => { getData('keyname').then(savedValue => { console.log(savedValue) savedValue && initialValues.setFieldValue('name', savedValue); }) }, []); return ( <Formik initialValues={initialValues.values} enableReinitialize> {({ values, setFieldValue }) => { const { name } = values; console.log(values) return <TextInput value={name} placeholder="write something..." onChangeText={e => { setFieldValue('name', e); storeData('keyname', e); }} /> } } </Formik> ) } export default CustomComponent

First we are going to use the hook provided by formik: useFormik ().首先我们要使用formik提供的钩子:useFormik()。 Now as parameters of that hook, we define an object with initial state properties.现在作为该钩子的参数,我们定义了一个具有初始状态属性的对象。

We will also use the useEffect hook, when the component is rendered, we use the getData function of the useAsyncStorage hook to obtain the values ​​stored in async storage and then we use the setFieldValue method to change the value of the property set in the first parameter and in the second we change the value for which we have in the async storage.我们还会用到useEffect hook,当组件渲染的时候,我们使用useAsyncStorage hook的getData函数来获取异步存储中存储的值,然后我们使用setFieldValue方法来改变属性中设置的值第一个参数,第二个参数我们更改我们在异步存储中的值。

Sorry if my English is bad.对不起,如果我的英语不好。 I am a Spanish speaker and I am using a translator我是说西班牙语的人,我正在使用翻译

Formik has a helper: setValues. Formik 有一个助手:setValues。

This is an example from the React web, but I'm sure it also works for Native.这是来自 React web 的示例,但我确信它也适用于 Native。

For example you could restore the values from local storage like @husdady explained.例如,您可以像 @husdady 解释的那样从本地存储中恢复值。 Not sure how Native does it, but you'll get the idea.不确定 Native 是如何做到的,但你会明白的。 You could also make a button "Save as draft" or you could save the draft in a effect hook when you leave the form, I demonstrate both cases below:您还可以制作一个“另存为草稿”按钮,或者您可以在离开表单时将草稿保存在效果挂钩中,我在下面演示了这两种情况:

const { handleSubmit, handleChange, setValues, values } = useFormik({
  initialValues: {
    name: "",
    email: "",
  },
  onSubmit: (values) => {
    // Your submit logic
    console.log(values);
  }
});

const saveAsDraft = () => {
  // store the values in local storage
  localStorage.setItem('form', JSON.stringify(values));
}

React.useEffect(() => {
  // Get the Formik values from local storage and restore
  const storage = localStorage.getItem('form');

  if(storage) {
    setValues(JSON.parse(storage));
  }

  // On unmount (e.g. leave the page) save the values
  return () => {
    saveAsdraft();
  }
}, [])

return (
  <form onSubmit={handleSubmit}>
    <input
      name="name"
      value={values.name}
      onChange={handleChange}
    />
    <input
      name="email"
      value={values.email}
      onChange={handleChange}
    />
    <button type="submit">Submit</button>
    <button onClick={() => saveAsDraft()}>Save as draft</button>
  </form>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM