reactjs - 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)} // 输出只是单个字母
我有点卡住了,因为我在项目的其他任何地方都使用了这个公式,但无法弄清楚为什么会存在这个错误。
解决方案
回答:
好的,正如 LPP 在评论中指出的那样, shouldComponentUpdate 正在抛弃它。重构了逻辑,它现在可以工作了。谢谢大家。
推荐阅读
- vue.js - 为什么 vue.js 为小图像渲染 base64 图像
- python - 替换字典列表中的一个字符并将对象返回到原始格式
- java - G1GC Old Gen 提交的堆不断增长,使用是恒定的 - 导致 Eden 饥饿
- json - 无法使用 utf8 编码上下文
- apache-kafka - 为什么 apache kafka 不使用标准的 java doc?
- javascript - 在 Javascript 中指定变量类型(用于解析目的)
- c# - 如何仅在部分布局上使用 WPF DataTemplates
- python-3.6 - 使用 Perforce 在 p4python 中复制命令
- scheme - 添加括号更改条件评估
- java - 根据十进制度数位置计算仪表偏移