【问题标题】:React: The existing value of my text input gets cleared when onChange event occurs反应:当 onChange 事件发生时,我的文本输入的现有值被清除
【发布时间】:2019-10-06 20:03:53
【问题描述】:

我是 Reactjs 的新手。我正在尝试创建一个页面,用户可以在其中编辑自己的帖子。因此,文本输入的值是用户在发布帖子时输入的值。现在,当我尝试更改文本输入中的现有文本时,表单中可用的值会被清除,用户必须重新输入数据。

我需要用户更改输入文本中的现有文本,而不是重新输入。这是我的代码。

import React, { Component } from 'react'

class EditProduct extends Component {
    constructor(props) {
        super(props)
        this.state = {
            product: []
        }

        this.handleChange = this.handleChange.bind(this)
    }
    componentDidMount() {
        fetch("http://localhost:8000/lender/edit_product_display.php?id=" + this.props.match.params.productId)
            .then(response => response.json())
            .then((productResponse) => {
                this.setState({
                   product: productResponse
                })
            })
            .catch(error => console.log(error))
    }
    handleChange(event){
        const name = event.target.name

        this.setState({
            product: [{
                [name]: event.target.value
            }]
        })
    }
    render() {
        return(
            <div key={this.state.product.product_id}>
                Product ID: {this.props.match.params.productId}
                <br /><br />
                Product Name:
                <input
                    type="text"
                    name="product_name"
                    value={this.state.product.product_name}
                    onChange= {this.handleChange}
                />

                <br />
                Product Model:
                <input 
                    type="text"
                    name="product_model"
                    value={this.state.product.product_model}
                    onChange={this.handleChange}
                 />
            </div>
            )
    }
}

export default EditProduct

【问题讨论】:

  • 您的值value={this.state.product.product_name} 与您用于状态的结构不匹配,即产品设置为数组product: [] 您的值需要反映这一点,例如this.state.product[0].product_name 或更改您的状态结构

标签: javascript reactjs


【解决方案1】:

React 只会在顶层自动合并状态。它不会为您合并到 product 中,因此您必须自己做:

    handleChange(event){
        const name = event.target.name
        const value = event.target.value

        this.setState(prevState => ({
            product: {
                ...prevState.product,
                [name]: value
            }
        }))
    }

【讨论】:

  • 我的文本输入仍然会清除现有值,并且整个状态会再次更新:(
  • @SarathDev 哦,我现在明白了。我在那里留下了一个不必要的数组。立即尝试。
  • 终于成功了!我已经坐这个很久了。非常感谢:)你让我开心! :D
猜你喜欢
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多