React hook useState 不使用 onSubmit 更新 [英] React hook useState not updating with onSubmit

查看:63
本文介绍了React hook useState 不使用 onSubmit 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在将输入字段值推送到 onSubmit 状态时遇到问题.

codesandbox

我正在尝试为状态设置一个输入字段值,以便在组件更新后我可以使用该值将用户重定向到另一个页面.我手动测试了路径并且它可以工作,但是由于状态不是同步更新,因此重定向不起作用.我可以在页面上呈现输入值,但是如果我尝试记录它,它会长时间未定义(第一次)和第二次提交时的先前状态.

import React, { useRef, useState } from "react";从../firebase"导入 { db };从@reach/router"导入{重定向};功能创建项目(道具){const [id, setID] = useState(null);const colorRef = useRef(null);const projectNameRef = useRef(null);const handleSubmit = e =>{e.preventDefault();const 项目 = {名称:projectNameRef.current.value,颜色:[colorRef.current.value],颜色名称:颜色名称Ref.current.value,createdAt: 新日期()};setID(projectNameRef.current.value);db.collection("用户").doc(`${props.user}`).collection("项目").doc(`${projectNameRef.current.value}`).set({ ...项目});e.target.reset();};返回标识?(<Redirect from="/projects/new" to={`projects/:${id}`} noThrow/>) : (<div><div><h1>创建新选择</h1><form onSubmit={handleSubmit}><label>颜色</label><input ref={colorNameRef} type="text" name="colorName"/><label>项目名称</label><input ref={projectNameRef} type="text" name="projectName" required/><button type="submit">提交</button></表单>

);}导出默认创建项目;

反应:16.8.6

解决方案

这就是 react hooks useState 的工作方式,要在状态更改后执行某些操作,您应该在 useEffect<中执行它/strong> 钩子,如下所示:

useEffect(() => {如果(ID){控制台日志(ID);projectNameRef.current.value = ''}}, [ID])

每次 id 值更改时(以及在第一次渲染中),此效果都会运行,因此您可以在此处添加逻辑并根据状态更改执行所需的操作.

I'm currently experiencing an issue pushing the input field value to state onSubmit.

codesandbox

I'm trying to set an input field value to the state so that I can use that value once the component is updated to redirect the user to another page. I tested the path manually and it works, but since the state is not updating synchronously, the redirect does not work. I can render the input value on the page, but if I try to log it, it long undefined(for the first time) and the previous state on a second submit.

import React, { useRef, useState } from "react";
import { db } from "../firebase";
import { Redirect } from "@reach/router";

function CreateProject(props) {
  const [id, setID] = useState(null);
  const colorRef = useRef(null);
  const projectNameRef = useRef(null);

  const handleSubmit = e => {
    e.preventDefault();
    const project = {
      name: projectNameRef.current.value,
      colors: [colorRef.current.value],
      colorName: colorNameRef.current.value,
      createdAt: new Date()
    };
    setID(projectNameRef.current.value);

    db.collection("users")
      .doc(`${props.user}`)
      .collection("projects")
      .doc(`${projectNameRef.current.value}`)
      .set({ ...project });
    e.target.reset();
  };


  return id ? (
    <Redirect from="/projects/new" to={`projects/:${id}`} noThrow />
  ) : (
    <div>
      <div>
        <h1>Create new selection</h1>
        <form onSubmit={handleSubmit}>
          <label>Color</label>
          <input ref={colorNameRef} type="text" name="colorName" />
          <label>Project Name</label>
          <input ref={projectNameRef} type="text" name="projectName" required />
          <button type="submit">Submit</button>
        </form>
      </div>
    </div>
  );
}

export default CreateProject;

react: 16.8.6

解决方案

That's the way react hooks useState works, to do something after a state change you should perform it inside a useEffect hook, like the following:

useEffect(() => {
  if (id) {
    console.log(id);
    projectNameRef.current.value = ''
  }
}, [id])

This effect will run every time the id value changes (and in the first render) so you could add your logic there and perform your desired actions based on the state change.

这篇关于React hook useState 不使用 onSubmit 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆