【问题标题】:Input not changing state REACTJS输入不改变状态 REACTJS
【发布时间】:2019-03-18 12:44:26
【问题描述】:

输入不会改变它的文本。它是从数据库中预先填充的。例如,如果它带有文本:example,如果我按下例如s 键,它会在控制台记录examples,但在DOM 中仍然是example。这是handle 代码:

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
    console.log(event.target.name);
    console.log(event.target.value);
  };

和输入字段:

<input 
  type="text" 
  className="form-control" 
  name="note" 
  id=" note" 
  value={this.state.insurance.note} 
  onChange={this.handleChange}
/>

EDIT修复了渲染问题,但是我在提交表单时没有得到我想要的数据) 这是我的表单的代码:

handleSubmit = event => {
    event.preventDefault();
    var state = this.state;
    axios
      .put(`${API_URL}/` + state.id + `/update`, {
        tip: state.tip,
        date_exp: state.date_exp,
        date_notif: state.date_notif,
        note: state.note
      })
      .then(response => {
        console.log(response.data);
        // window.location = "/view";
      })
      .catch(error => {
        console.log(error);
      });
  }

我的按钮是一个简单的提交按钮:

<button className="btn btn-success" type="submit">Save</button>

【问题讨论】:

    标签: javascript reactjs forms input


    【解决方案1】:

    imjared 的回答是正确的:您的问题出在 handleChange 函数中,您错误地更新了状态。
    该函数应该类似于以下函数:

    handleChange = event => {
        const insurance = Object.assign({}, this.state.insurance);
        insurance[event.target.name] = event.target.value;
    
        this.setState({insurance});
      };
    

    在函数的第一行,您创建了当前对象insurance 保存在状态中的深层副本。然后,更新复制的对象,最后更新状态。

    【讨论】:

    • 问题是,现在当我提交表单时,它console.loges 和空对象...在它之前console.loged 和对象与我修改过的文件...跨度>
    • 能否请您也发布提交按钮的代码? :)
    • 好吧,如果您的意思是 console.log(response.data) 返回一个空对象,这取决于无法正常工作的 fetch。通过查看您的请求,我确实想知道:您是否应该写state.insurance.date_expstate.insurance.date_notif 而不是state.date_exp...?我的意思是,在您处理 insurance 对象的更改之前,但在该请求中,您似乎没有任何 insurance 对象处于状态
    • 是的,你是对的,很抱歉这个愚蠢的问题......就是这样......非常感谢!
    • 谢谢你! ;)
    【解决方案2】:

    您正在根据输入的name 属性更改this.state.note,因此this.state.insurance.note 看不到任何更新是有道理的。

    如果您在&lt;input&gt; 上方尝试使用console.logging this.state,我敢打赌您会看到您所追求的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2019-05-31
      • 1970-01-01
      • 2014-11-06
      • 2021-09-27
      • 2019-04-29
      • 2023-01-02
      相关资源
      最近更新 更多