首页 > 解决方案 > React handlechange 只是更新每个字母而输入没有意识到它

问题描述

好吧,我放弃了,需要帮助。

之前在许多项目上都这样做过,但似乎无法弄清楚为什么我的状态表现不正确。这是以下重要的代码位。问题是它改变了状态,但只改变了输入的最后一个字母。而且它没有反映在输入框中(它保持空白)

import React, { Component } from "react";

class PublicMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
  
  shouldComponentUpdate(nextProps, nextState) {
    let center = this.olmap.getView().getCenter();
    let zoom = this.olmap.getView().getZoom();
    if (center === nextState.center && zoom === nextState.zoom) return false;
    return true;
  }


  handleChange(e){
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  
  render() {
    return (
      <>
        <div
          id="map"
          style={{ width: "100%", height: "360px" }}
          className="container"
        >
          <br></br>
          <button
            className="btn btn-primary btn-sm"
            onClick={(e) => this.userAction()}
          >
            Draw New Polygon
          </button>
          <input
            type="text"
            value={this.state.name}
            onChange={this.handleChange.bind(this)}
            name="name"
          />
          <button
            type="submit"
            onClick={this.addName}
            className="btn btn-primary"
          >
            Add Name
          </button>

          <br></br>
          <br></br>
        </div>
      </>
    );
  }
}

export default PublicMap;

编辑:我添加了我相信的所有相关代码 编辑*:我不相信 shouldComponentUpdate() 会很重要,但为了以防万一,代码与其他内容有关。

我的问题是什么的例子。在输入框中输入内容不会显示任何内容,完全空白。

检查组件或控制台记录

handlechange(e){ console.log(e.target.value)} // 输出只是单个字母

我有点卡住了,因为我在项目的其他任何地方都使用了这个公式,但无法弄清楚为什么会存在这个错误。

标签: reactjs

解决方案


回答:

好的,正如 LPP 在评论中指出的那样, shouldComponentUpdate 正在抛弃它。重构了逻辑,它现在可以工作了。谢谢大家。


推荐阅读