React按钮onClick自动触发 点击传State值调用函数问题求助
问题根因
按钮onClick属性直接写apicall({name})属于立即执行函数的写法,组件每次渲染(包括state更新触发的重渲染)都会直接调用apicall,这就是你修改输入框就触发函数打印的原因。onClick需要接收一个函数引用,点击时才会执行。
修复方案
1. 完善Contact组件的state与事件绑定
给所有表单字段添加对应state,修改点击事件为回调函数写法,同时修正name的初始值(字符串类型输入框初始值不要设为数字0):
import React,{useState} from 'react'; import Section from '../../../HOC/Section'; import apicall from '../../UI/JS/allapicall.js'; const Contact = () => { // 给所有表单字段定义state,初始值设为空字符串 const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); return ( <Section id='contact'> <div className='container pt-2 pb-5'> <div className='section-header pt-5 pb-5 text-center'> <h3 className='section-title'> <span>Get in touch with </span>Us </h3> <h6 className='section-subtitle mr-auto ml-auto'> We are here with you </h6> </div> <div className='section-content'> <div className='row'> <div className='col-md-9 col-lg-7 mr-auto ml-auto'> <div className='form-group'> <input type='text' className='form-control rounded-0' aria-describedby='emailHelp' placeholder='Enter Name...' onChange={e=>setName(e.target.value)} /> </div> <div className='form-group'> <input type='email' className='form-control rounded-0' aria-describedby='emailHelp' placeholder='Enter email...' onChange={e=>setEmail(e.target.value)} /> </div> <div className='form-group'> <textarea className='form-control rounded-0' rows='5' placeholder='Enter Message...' onChange={e=>setMessage(e.target.value)} /> </div> <div className='form-group text-center'> {/* 用箭头函数包裹,点击时才执行apicall */} <button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={() => apicall({name, email, message})}> Send </button> </div> </div> </div> </div> </div> </Section> ); }; export default Contact;
2. 调整apicall函数(可选,如需把表单数据传给接口)
如果需要将表单参数提交到目标接口,可以把参数放到请求的params或者body中:
import axios from 'axios'; export default function messagesubmit(formData) { console.log(formData); // 注意:前端明文存储apikey有安全风险,建议改为后端代理转发请求 axios.get('https://www.zohoapis.com/crm/v2/functions/ticket_create/actions/execute?auth_type=apikey', { params: { zapikey: "1003.9145fb5d691b5f95a194c17e56300ed3.1cc7246813d8d6842c47f543a4f50b8f", // 把表单参数传到接口,参数名按接口要求调整即可 name: formData.name, email: formData.email, message: formData.message } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) }
提示:如果接口要求POST请求,把
axios.get改为axios.post,参数放到第二个参数即可。
内容的提问来源于stack exchange,提问作者NooB Gamer
相关产品推荐
相关产品推荐

