javascript - React - 即使屏幕上打印的消息发生更改,类组件中的状态也不会更新
问题描述
我有一个包含输入的App组件。每次我输入输入时,输入的值都会更新,并且消息组件会根据输入的长度打印不同的消息。同时,名为Character的第三个组件将字符串的每个字母单独打印到屏幕上。所需的行为是,当我单击其中一个字母时,它会从字符串中删除,新字符串会显示在屏幕上,并且输入也会使用新字符串进行更新。
我使用了一些 console.logs 进行调试,一切似乎都按预期进行,直到我尝试更新状态的最后一步,但由于某种原因,它没有得到更新。
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: "" };
}
render() {
const handleUpdateText = event => {
this.setState({
text: event.target.value
});
};
const inputLength = this.state.text.length;
const toArray = this.state.text.split("");
const handleDeleteLetter = index => {
toArray.splice(index, 1);
console.log(toArray);
const updatedArray = toArray.join("");
console.log(updatedArray);
this.setState({ text: updatedArray });
console.log(this.state.text);
};
return (
<>
<input type="text" onChange={handleUpdateText} />
<Message inputLength={inputLength} />
{toArray.map((letter, index) => (
<Character
key={index}
theLetter={letter}
deleteLetter={() => handleDeleteLetter(index)}
/>
))}
</>
);
}
}
class Message extends React.Component {
render() {
const { inputLength } = this.props;
let codeToPrint = "The text is long enough!";
if (inputLength <= 5) {
codeToPrint = "The text is not long enough!";
}
return <p>{codeToPrint}</p>;
}
}
class Character extends React.Component {
render() {
const { theLetter, deleteLetter } = this.props;
return (
<div
style={{
display: "inline-block",
padding: "16px",
textAlign: "center",
margin: "16px",
backgroundColor: "tomato"
}}
onClick={deleteLetter}
>
{theLetter}
</div>
);
}
}
完整的代码在这里:
我真的不明白我做错了什么,我觉得与生命周期方法有某种关系。任何答案都会有所帮助。谢谢你。
解决方案
状态正在更新,您只需将value
prop 传递给输入,以便输入的值可以与您的状态同步
<input type="text" value={this.state.text} onChange={handleUpdateText} />
而且您在设置后看不到更新的状态,因为它setState
是异步的。这就是为什么紧跟在console
语句之后的setState
语句显示前一个值的原因。
此外,您应该将函数移出渲染方法,因为每次您的组件重新渲染时,都会创建新函数。您可以将它们声明为类属性并传递它们的引用
handleUpdateText = event => {
this.setState({
text: event.target.value
});
};
render() {
.......
return (
<>
<input type="text" onChange={this.handleUpdateText} />
推荐阅读
- windows - 如何通过 Powershell 脚本运行运行命令
- python-3.x - OSError: 找不到 lib c 或加载它的任何变体 []。更新后的macos
- html - 带有水平子菜单栏显示/隐藏的导航栏下拉菜单
- python - 如何获得两列日期之间的差异?(我需要工作日,即不包括周末)
- python - 将 HTML 与 Flask 一起使用时,CSS 仅部分呈现?
- groovy - 从 Spock 迁移到 2.0 和 Groovy 迁移到 3.0.7 之后,@Category 测试未执行
- javascript - 带有 http 302 的 JS 服务工作者和缓存存储 API - 如何缓存重定向?
- scala - scala中的平衡括号递归方法
- php - 开关盒不适用于负检查
- postgresql - Postgresql 13 - 为组记录触发一次