简体   繁体   English

我如何使next.js表单输入字段中的数据在刷新页面后保留?

[英]How do i make the data in the input feild of my form in next js stay after refresh of the page?

I am working on a form in nextjs and i would love the data to remain the same ie persist after the entire page as been refreshed or reloaded.我正在 nextjs 中处理一个表单,我希望数据保持不变,即在刷新或重新加载整个页面后保持不变。 Local storage doesnt work with next.js, so i am looking for an alternative, i always get local storage not defined when i use it Here is my code below本地存储不适用于 next.js,所以我正在寻找替代方案,当我使用它时,我总是得到未定义的本地存储这是我下面的代码

import React, { useState, useEffect, useLayoutEffect, createContext , useContext } from "react";
import { useRouter } from "next/router";
import Cookie from "js-cookie";
import { parseCookies } from "../helpers/index";
import { Formik } from "formik";
function Form() {
  return (
      <div>
      <form action="" >
        <section class="left">
          <div class="input-container">
            <label for="name">Full name</label>
            <input type="text"/>
          </div>
          <div class="input-container">
            <label for="age" required>
              Mobile Number
            </label>
            <input type="text"/>
          </div>
          <div class="input-container">
            <label for="phone">Choose password</label>
            <input type="text"/>
          </div>
          </div>
        </section>
      </form>
    </div>
  );
}

export default Form;

With formik out of the question, to let data persist after refresh, you need to save it to localStorage ( or cookies ).有了 formik 就不可能了,要让数据在刷新后保持不变,您需要将其保存到 localStorage(或 cookies)。

This works for NextJS (you need to test for window first)这适用于 NextJS(您需要先测试window

Example as follows示例如下

const App = () => {
     const [ value, setValue ] = useState({
                                     name: '',
                                     mobile: '' 
                                 });

     useEffect(() => {
          //you need to call this for nextjs, so this is performed only on client side.
          if (typeof window !== 'undefined') {
               let storedValue = localStorage.getItem('value');
               if (storedValue) {
                   storedValue = JSON.parse(storedValue) || {}
                   // we explicitly get name and mobile value in case localStorage was manually modified.
                   const name = storedValue.name || ''
                   const mobile = storedValue.mobile || ''
                   setValue({ name, mobile }) //restore value from localStorage
               }
          

          }
        
     },[]) 

     // alternatively a betterway to handle side effect is useEffect
     // useEffect(() => {
     //   localStorage.setItem('value', JSON.stringify(value))
     // },[value])
     
     const onChange = (e) => {
         const name = e.target.name
         
         const newValue = { ...value, [name]: e.target.value }
         setValue(newValue);
         localStorage.setItem('value', JSON.stringify(newValue)) //save input to localstorage
     }

     return (<div>
              <input name="name" value={value.name} onChange={onChange} />
              <input name="mobile" value={value.mobile} onChange={onChange} />
             </div>
      ) 
 
   }


}

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

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