Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React:使用spread操作符使用表单数据onChange更新状态_Javascript_Reactjs - Fatal编程技术网

Javascript React:使用spread操作符使用表单数据onChange更新状态

Javascript React:使用spread操作符使用表单数据onChange更新状态,javascript,reactjs,Javascript,Reactjs,我试图使用spread操作符更新我的状态,这样我就可以在http请求中传递表单数据,但从我在console.logs中看到的情况来看,它似乎根本没有更新 我还收到错误“TypeError:传播不可iterable实例的尝试无效”。我需要我传入的数据成为一个对象 import React from 'react' import SuperAgent from 'superagent' import { string } from 'prop-types' class ContactForm ex

我试图使用spread操作符更新我的状态,这样我就可以在http请求中传递表单数据,但从我在console.logs中看到的情况来看,它似乎根本没有更新

我还收到错误“TypeError:传播不可iterable实例的尝试无效”。我需要我传入的数据成为一个对象

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'
}
从“React”导入React
从“SuperAgent”导入SuperAgent
从“属性类型”导入{string}
类ContactForm扩展了React.Component{
建造师(道具){
超级(道具)
this.handleClick=this.handleClick.bind(this)
this.onChange=this.onChange.bind(this)
this.submitForm=this.submitForm.bind(this)
此.state={
数据:{}
}
}
handleClick(e){
e、 预防默认值()
this.submitForm()
}
onChange(e){
this.setState(…this.state.data,{[e.target.name]:e.target.value})
}
提交形式(){
const{data}=this.state
超级药剂
.post('https://something.com')
.set('Content-Type','application/json')
.发送({
数据:{
'name':'name',
'formName':'form',
'emailName':'email',
数据
}})
.end((错误、恢复)=>{
if(err | | |!res | |!res.body)返回console.log(err)
window.location='/contact form successful.html'
})
}
渲染(){
返回(
发送数据!
)
}
}
导出默认联系人表单
ContactForm.propTypes={
id:字符串
}
ContactForm.defaultProps={
id:“联系方式”
}

扩展运算符的正确语法用法如下所示:

  onChange (e) {
    this.setState({...this.state.data, [e.target.name]: e.target.value })
  }
  onChange (e) {
    this.setState({[e.target.name]: e.target.value })
  }
但是,您不需要使用
setState
进行扩展,您只需要更新需要更新的内容

因此,您将只设置如下状态:

  onChange (e) {
    this.setState({...this.state.data, [e.target.name]: e.target.value })
  }
  onChange (e) {
    this.setState({[e.target.name]: e.target.value })
  }
如果要依赖先前的状态值,则必须使用functional
setState

  onChange (e) {
    this.setState(prevState => ({...prevState, [e.target.name]: e.target.value }))
  }
除此之外,您还缺少要从react组件的状态检索的输入值,而不是将其硬编码为
'
空字符串,因此,当您的状态不断用最后一个键输入更新时,值从未反映在输入中

        <input
          name="username"
          type="text"
          value={this.state.username}
          onChange={this.onChange}
        />
        <input
          name="email"
          type="email"
          value={this.state.email}
          onChange={this.onChange}
        />
        <input
          name="birthdate"
          type="text"
          value={this.state.birthdate}
          onChange={this.onChange}
        />

您使用的
setState
错误

this.setState(...this.state.data, {[e.target.name]: e.target.value })
应该是

 const { target : { value, name } } = e
 this.setState(prevState => ({
     data: {
        ...prevState.data,
        [name]: value
     }
 }))
此外,输入的
应反映
状态
(受控输入)


您的onChange方法应该这样做:

 onChange (e) {
    this.setState(state => ({
        data: {
           ...state.data,
           [e.target.name]: e.target.value
        }
    }))
  }


您正在更新整个状态,而不仅仅是state.data属性。请参阅,您的输入不受控制。我更新了我的答案。现在该工作了!非常感谢。这是有效的:)谢谢,它不会让我用这些解决方案键入输入框?您还必须将每个输入值设置为其各自的状态属性这是另一个问题,以及第一个语法问题,使用正确的输入绑定更新了答案。它相当于单向数据绑定,状态值反映在相应的
输入中
实际上这里的正确术语是受控的。但你是对的,这根本不是双向的