使用 React Hooks 创建具有多个输入的 axios 帖子 [英] Create an axios post with multiple inputs using React Hooks

查看:15
本文介绍了使用 React Hooks 创建具有多个输入的 axios 帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用 React 并开始使用类并决定改用 Hooks.我相信我已经正确地绘制了所有内容,但是我非常不确定如何使用 useEffect 构建我的 axios.post 以处理多个用户输入.

import React, { useState, useEffect } from 'react'从 'axios' 导入 axiosconst 注册 = () =>{const [customerSignUp, setCustomerSignUp] = useState([{电子邮件:'',密码:'',名字:'',姓氏:''}]);const handleChange = (事件) =>{setCustomerSignUp(event.target.value)}const handleSubmit = (e) =>{e.preventDefault()控制台日志(e)}useEffect(() => {axios.post('/api/Customer/SignUp', {}).then(功能(响应){控制台日志(响应)}).catch(函数(错误){控制台日志(错误)})}, [])

我只包含 lastName 来展示我如何使用 handleChange 事件处理程序来更改客户的状态.

 返回 (<div className="容器"><form className='white' onSubmit={handleSubmit}><h5 className="grey-text.text-darken-3">使用电子邮件注册</h5><div className="输入字段"><label htmlFor="lastName">姓氏</label><input type="text" name="lastName" value={customerSignUp.lastName} onChange={handleChange} required/>

<div className="输入字段"><button className="btn blue darken-3" type="submit">注册</button>

</表单>

);}导出默认注册

解决方案

您的 axios 请求不必在 useEffect() 内,实际上与您的注册功能,最好将其保存在您的 handleSubmit 函数中.您可以选择将 useEffect() 设置为在第一次组件渲染后或每次更改特定依赖项后触发一次.两者都不是特别适合您的功能.

此外,让您的状态保存一个对象而不是一组对象似乎更有意义.从那里,您可以像这样将您的状态放入 axios 请求中:

import React, { useState, useEffect } from 'react'从 'axios' 导入 axiosconst 注册 = () =>{const [customerSignUp, setCustomerSignUp] = useState({电子邮件:'',密码:'',名字:'',姓氏:''});const handleChange = (事件) =>{setCustomerSignUp({...customerSignUp, [event.target.name]: event.target.value})}const handleSubmit = (e) =>{e.preventDefault()axios.post('/api/Customer/SignUp', customerSignUp).then(功能(响应){控制台日志(响应)}).catch(函数(错误){控制台日志(错误)})

setCustomerSignUp({ email: '', password: '', firstName: '', lastName: '' });}

还要记住为每个输入赋予一个名称属性,该属性对应于状态中的一个字段.(看起来你已经有了)

 返回 (<div className="容器"><form className='white' onSubmit={handleSubmit}><h5 className="grey-text.text-darken-3">使用电子邮件注册</h5><div className="input-field"><label htmlFor="lastName">Last Name</label><输入类型=文本"姓名=姓氏"value={customerSignUp.lastName} onChange={handleChange} 需要/>

<div className="input-field"><button className="btn blue darken-3";type="submit">注册</button>

</表单>

);}导出默认注册

I am learning how to use React and started using classes and decided to swap over to using Hooks. I believe that I have everything mapped out correctly, however I am very uncertain of how to structure my axios.post with useEffect to handle multiple user inputs.

import React, { useState, useEffect } from 'react'
import axios from 'axios'

const Signup = () => {
    const [customerSignUp, setCustomerSignUp] = useState([
        { email: '', password: '', firstName: '', lastName: ''}
    ]);

    const handleChange = (event) => {
        setCustomerSignUp(event.target.value)
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log(e)
    }

    useEffect(() => {
        axios.post('/api/Customer/SignUp', {

        })
        .then(function (response) {
            console.log(response)
        })
        .catch(function (error) {
            console.log(error)
        }) 

    }, [])

I included just the lastName to show how I am using the handleChange event handler to change the state of the customer.

    return (
        <div className="container">
            <form className='white' onSubmit={handleSubmit}>
                <h5 className="grey-text.text-darken-3">Sign Up With Email</h5>                        
                <div className="input-field">
                    <label htmlFor="lastName">Last Name</label>
                    <input type="text" name="lastName" value={customerSignUp.lastName} onChange={handleChange} required />
                </div>
                <div className="input-field"> 
                    <button className="btn blue darken-3" type="submit">Sign Up</button>
                </div>
            </form>
        </div>
    );
}
export default Signup

解决方案

Your axios request doesn't have to be inside a useEffect(), in fact with your sign-up feature, it probably is best to keep it in your handleSubmit function instead. You have the option to set useEffect() to trigger a single time after first component-render or after every change to a particular dependency. Neither is particular suitable for your feature.

Additionally, it seems like it would make more sense to have your state hold an object, not an array of objects. From there, you can just drop your state into the axios request like this:

import React, { useState, useEffect } from 'react'
import axios from 'axios'

const Signup = () => {
    const [customerSignUp, setCustomerSignUp] = useState(
        { email: '', password: '', firstName: '', lastName: ''}
    );

    const handleChange = (event) => {
        setCustomerSignUp({...customerSignUp, [event.target.name]: event.target.value})
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        axios.post('/api/Customer/SignUp', customerSignUp)
          .then(function (response) {
              console.log(response)
          })
          .catch(function (error) {
              console.log(error)
          }) 

setCustomerSignUp({ email: '', password: '', firstName: '', lastName: '' }); }

Also remember to give a name attribute to each input that corresponds to a field in the state. (Which looks like you already have)

    return (
        <div className="container">
            <form className='white' onSubmit={handleSubmit}>
                <h5 className="grey-text.text-darken-3">Sign Up With Email</h5>                        
                <div className="input-field">
                    <label htmlFor="lastName">Last Name</label>
                    <input type="text" name="lastName" value={customerSignUp.lastName} onChange={handleChange} required />
                </div>
                <div className="input-field"> 
                    <button className="btn blue darken-3" type="submit">Sign Up</button>
                </div>
            </form>
        </div>
    );
}
export default Signup

这篇关于使用 React Hooks 创建具有多个输入的 axios 帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆