如何使用带有React Hooks的axios来发布请求?

理查德·鲁布列夫(Richard Rublev)

这是我的Signupcomponent

const SignupComponent = () => {
    const [values, setValues] = useState({
        username: 'silvio1',
        name: 'Silvioo',
        email: '[email protected]',
        password: '123ooo007',
    });
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();

        const { username, name, email, password } = values;
        const user = {username, name, email, password};

        await axios.post('${API)/signup', user);        
    };

    const handleChange = name => e => {
        setValues({ ...values, [name]: e.target.value });
    };

    const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');

    const signupForm = () => {
        return (
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <input
                        value={values.username}
                        onChange={handleChange('username')}
                        type="text"
                        className="form-control"
                        placeholder="Type your username"
                    />
                </div>

                <div className="form-group">
                    <input
                        value={values.name}
                        onChange={handleChange('name')}
                        type="text"
                        className="form-control"
                        placeholder="Type your name"
                    />
                </div>

                <div className="form-group">
                    <input
                        value={values.email}
                        onChange={handleChange('email')}
                        type="email"
                        className="form-control"
                        placeholder="Type your email"
                    />
                </div>

                <div className="form-group">
                    <input
                        value={values.password}
                        onChange={handleChange('password')}
                        type="password"
                        className="form-control"
                        placeholder="Type your password"
                    />
                </div>

                <div>
                    <button className="btn btn-primary">Signup</button>
                </div>
            </form>
        );
    };

    return <React.Fragment>
        {showLoading()}
        {signupForm()} 
         </React.Fragment>;
};

export default SignupComponent;

编辑我更改了我的代码(zhulien接受的答案)。出现注册页面,我尝试注册用户。我有错误

Unhandled Runtime Error
Error: Request failed with status code 404

Call Stack
createError
node_modules/axios/lib/core/createError.js (16:0)
settle
node_modules/axios/lib/core/settle.js (17:0)
XMLHttpRequest.handleLoad
node_modules/axios/lib/adapters/xhr.js (62:0)

前端文件夹

components
config.js
next.config.js
node_modules
package.json
package-lock.json
pages

我的页面文件夹

_document.js
index.js
signin.js
signup.js

signup.js导入上面的代码

import Link from 'next/link';
import Layout from '../components/Layout';
import SignupComponent from '../components/frontauth/SignupComponent';

const Signup = () => {
    return (
        <Layout>
            <h2>Signup page</h2>
            <SignupComponent />
        </Layout>
    );
};

我的next.config.js

{
  APP_NAME: 'BLOG FRONTEND',
  APP_DEVELOPMENT: 'http://localhost:3000',
  PRODUCTION: false
}

和config.js

const { publicRuntimeConfig } = getConfig();

console.log(publicRuntimeConfig);
export const API = publicRuntimeConfig.PRODUCTION
    ? 'https://cryptoblog.com'
    : 'http://localhost:3000';
export const APP_NAME = publicRuntimeConfig.APP_NAME;

我是React和React Hooks的新手。如何解决这个问题呢?

朱莲

首先,您要尝试访问{username}(不存在)而不是state属性(即)values.username此外,不要在事件处理程序中使用钩子,它们应该在组件的顶层主体中或仅在自定义钩子中使用。签出此:React钩子规则

所以:

  1. 在您的表单中,您必须使用state(values)属性。
  2. 提取useEffect组件主体流程中的钩子或更好地将其完全删除,因为您当前未正确使用它。您最好使用简单的表单提交事件处理程序,该事件处理程序应该在不设置任何状态的情况下将数据发布到某个地方。

您的代码可能类似于:

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { API } from '../../config';

const SignupComponent = () => {
    const [values, setValues] = useState({
        username: 'silvio1',
        name: 'Silvioo',
        email: '[email protected]',
        password: '123ooo007',
    });

    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();

        const { username, name, email, password } = values;
        const user = {username, name, email, password};

        await axios.post('${API)/signup', user);        
    };

    const handleChange = name => e => {
        setValues({ ...values, [name]: e.target.value });
    };

    const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');

    const signupForm = () => {
        return (
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <input
                        value={values.username}
                        onChange={handleChange('username')}
                        type="text"
                        className="form-control"
                        placeholder="Type your username"
                    />
                </div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React:带有参数和正文的axios发布请求

-u在CURL中的含义是什么,以及如何使用带有-u的restTemplate来发布请求

如何使用带有 Spring Boot 后端的 React JS、Axios 发布多个对象?

如何正确使用带有 axios + react 的拦截器

如何解决Axios发布请求的问题

使用 Axios 发布请求的 JWT 授权

如何修复Axios获取请求和React Hooks?

如何使用Rails发送带有Ajax发布请求的表单

React应用中的Axios 带有表单数据的图像发布带有空正文的请求

如何在 React 中使用带有字符串数组的循环简单地请求 axios.all?

在带有 React Hooks 的 react-table 中,如何在 Cell 内发出 get 请求?

如何正确更新表单,使用 axios 发布请求响应状态?

如何发布正确的请求以使用 axios 表达路由?

如何在反应中使用 axios 发布请求

如何为提供者使用带有多个值的React Hooks上下文

如何使用 React Hooks 将带有构造函数的类转换为函数式组件?

如何在 React 上使用 axios 执行发布请求并将数据作为 FormData 传递?

如何使用带有flowtype的React $ Element以外的其他类型来键入JSX?

Axios发布请求在React Native中不起作用

Axios在vuex操作中发布具有多个参数的请求

如何从axios发布请求中获取PHP中的变量

如何使用python请求模块发送带有数据的发布请求?

使用axios将FormData作为参数传递给发布请求

使用axios发布请求时出现网络错误

从URL提取令牌并使用Axios发送发布请求-Vue js

使用 400 或 401 在 Axios 中发布请求 - 不记名令牌

使用Axios发出发布请求时出现网络错误

在后端使用laravel发布带有react的请求ajax

使用带有大量数据的发布请求来调用servlet,并在新标签页中打开url