首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >输入电子邮件字段onchange不将字符串设置为state if last字段

输入电子邮件字段onchange不将字符串设置为state if last字段
EN

Stack Overflow用户
提问于 2020-09-07 23:45:44
回答 1查看 51关注 0票数 0

这真的很奇怪,我将一个电子邮件输入设置为字符串状态,我可以在react dev工具上看到它被发送,但如果我试图从另一个函数记录它,我得到空字符串,事情是,如果我改变输入的顺序,并且电子邮件不是最后一个,那么一切都会正常工作。

代码语言:javascript
运行
复制
import React, { useState, useEffect, useCallback, useContext } from 'react'
import { useDropzone } from 'react-dropzone'
import context from '../provider/context'
import axios from 'axios'

const File = () => {

  const { setStage, setProject, project, setUrls, urls, email, setEmail } = useContext(context)

  const onDrop = useCallback((acceptedFiles) => uploadFile(acceptedFiles), [project])

  const { getRootProps, isDragActive, getInputProps } = useDropzone({ onDrop })


  // Set project name
  const addProject = (e) => setProject(e.target.value)

  // Set email address
  const addEmail = (e) => setEmail(e.target.value)

  // I got another function then that logs the `email` state, 
  // but if I do it right after typing on the email input I get empty  string.
  // If I invert the order, and `project` comes after the email input 
  // then it displays the email string just fine.


 return (
    <>
      <ul className='list'>
        <li>
          <label className='label' htmlFor='upload'>
            Project's Name
          </label>
          <input
            id='upload'
            value={project}
            type='text'
            name='project'
            placeholder='e.g Great Project'
            onChange={addProject}
            autoFocus
          />
        </li>
        <li>
          <label className='label' htmlFor='email'>
            Your email address
          </label>
          <input
            id='email'
            type='email'
            name='email'
            value={email}
            placeholder='Email address to send notification to'
            onChange={addEmail}
          />
        </li>
      </ul>

      <div className='fileTitle' {...getRootProps()}>
          {isDragActive ? <p className='label'>Drop the file here ...</p> : handleResponse()}
          <div className='file'>
            <div id='drop-area' className={`drop-area ${isDragActive ? 'active' : ''}`}>
              <div className={`icon ${response ? response : ''}`}></div>
            </div>
            <input
              {...getInputProps()}
              className='inputfile'
              id='file'
              type='file'
              name='locations'
            />
          </div>
          <br />
          <em className='info'>
            * Don’t include any headers in the file, just your list of urls with{' '}
            <strong>no headers</strong>.
          </em>
        </div>
   </>
)}

export default File

记录电子邮件的函数使用react-dropzone插件

代码语言:javascript
运行
复制
 // Upload file
  const uploadFile = async (file) => {
    console.log(email)
    const formData = new FormData()
    formData.append('urls', file[0])

    try {
      const options = {
        headers: { 'content-type': 'multipart/form-data' },
        params: { project, email }
      }

      const res = await axios.post('/api/upload/', formData, options)

      setUrls(res.data.number)
      setResponse('success')

      setTimeout(() => setStage('process'), 1200)
    } catch (err) {
      setResponse(err.response.data)
    }
  }

做一个简单的onclick可以很好的工作

代码语言:javascript
运行
复制
const checkEmail = () => {
 console.log(email) // This works cause it takes it form the useContext
}

然后在html上

代码语言:javascript
运行
复制
<button onClick={checkEmail}>Click here<button>
EN

回答 1

Stack Overflow用户

发布于 2020-09-08 00:53:30

最后,我需要将email作为数组依赖项添加到react-drop区域useCallback中,以便它可以注册该状态发生了变化。

所以我改变了:

代码语言:javascript
运行
复制
const onDrop = useCallback((acceptedFiles) => 
  uploadFile(acceptedFiles), [project])

代码语言:javascript
运行
复制
const onDrop = useCallback((acceptedFiles) => 
  uploadFile(acceptedFiles), [project, email])

这就是为什么,当我在添加电子邮件后更改项目字段时,它是有效的。

非常感谢@NateLevin,他帮助我找到了问题所在。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63780697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档