【发布时间】:2019-09-26 14:16:46
【问题描述】:
我正在尝试使用扩展运算符更新我的状态,以便可以在 http 请求中传递表单数据,但从我在 console.logs 中看到的内容来看,它似乎根本没有更新。
我还收到错误“TypeError:传播不可迭代实例的无效尝试”。不过,我需要将传入的数据作为对象。
import React from 'react'
import SuperAgent from 'superagent'
import { string } from 'prop-types'
class ContactForm extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.onChange = this.onChange.bind(this)
this.submitForm = this.submitForm.bind(this)
this.state = {
data: {}
}
}
handleClick (e) {
e.preventDefault()
this.submitForm()
}
onChange (e) {
this.setState(...this.state.data, {[e.target.name]: e.target.value })
}
submitForm () {
const { data } = this.state
SuperAgent
.post('https://something.com')
.set('Content-Type', 'application/json')
.send({
data: {
'name': 'name',
'formName': 'form',
'emailName': 'email',
data
}})
.end((err, res) => {
if (err || !res || !res.body) return console.log(err)
window.location='/contact-form-successful.html'
})
}
render () {
return (
<section className='contact-form' id={this.props.id}>
<form id='contact-form' method='post' action='#' onSubmit={this.handleClick}>
<input
name="username"
type="text"
value=''
onChange={this.onChange}
/>
<input
name="email"
type="email"
value=''
onChange={this.onChange}
/>
<input
name="birthdate"
type="text"
value=''
onChange={this.onChange}
/>
<button>Send data!</button>
</form>
</section>
)
}
}
export default ContactForm
ContactForm.propTypes = {
id: string
}
ContactForm.defaultProps = {
id: 'contact-form'
}
【问题讨论】:
-
您的输入不受控制。我更新了我的答案。现在应该可以了!
-
谢谢!有效:)
标签: javascript reactjs