reactjs - 调用 setState 后反应状态不会改变
问题描述
我对 React 相当陌生,并试图理解状态的概念。我正在尝试像终端一样依次拥有一组输入字段
页面组件如下所示
import React, { Component } from "react";
import NewLine from "./newLine";
export class Page extends Component {
state = {
numberOfLine: 0,
lines: [{ value: "", id: 0 }]
};
render() {
return (
<div className="container">
<div className="terminal">
<p className="prompt">
Hey there! This is a pre rendered line.
</p>
{this.state.lines.map(l => (
<NewLine
key={this.state.numberOfLine}
handelWhatever={this.handelWhatever}
line={l}
></NewLine>
))}
</div>
</div>
);
}
handelWhatever = (string_value, LId) => {
console.log(string_value, lId);
this.setState(
{
lines: [
...this.state.lines.filter(line => line.id !== lId),
{ value: string_value, id: lId}
]
},
() => this.handleClick()
);
};
// Adding a new line after a click
handleClick = event => {
const num = this.state.numberOfLine + 1;
this.setState({
numberOfLine: num,
lines: [...this.state.lines, { value: "", id: num }]
});
};
}
export default Page;
我的NewLine
组件看起来像这样
import React, { Component } from "react";
export class NewLine extends Component {
state = {
id: this.props.line.id,
value: this.props.line.value,
displayInput: true
};
render() {
return (
<React.Fragment>
<p className=output>
{this.state.displayInput && (
<input
type="text"
className="here"
value={this.state.value}
onChange={this.handleChange}
onKeyDown={this.handelEnter}
/>
)}
{this.state.value}
</p>
</React.Fragment>
);
}
handleChange = event => {
this.setState({ value: event.target.value });
};
handelEnter = event => {
if (event.key === "Enter") {
this.setState({displayInput : false})
this.props.handelWhatever(event.target.value, this.state.id);
}
};
}
export default NewLine;
当我在输入中输入“某事”时,它应该创建一个 NewLine 组件并从前一个组件中删除输入,以便用户可以在新呈现的行上键入,这就是为什么我在 New Line 状态下有 bool,但 bool 确实即使console.log("Did bool change")
打印也不会改变,我也给 setState 一个回调函数
this.setState({ displayInput: false }, () => console.log(this.state))
它更新状态并displayInput
为假,但在反应控制台中它仍然显示 displayInput 为真
还是有另一种方法可以做到这一点?
谢谢你的帮助干杯
解决方案
推荐阅读
- r - 零膨胀模型 R 二进制部分的响应曲线
- python - 如何在 15 天范围内的网站上使用 selenium 遍历日期范围?
- python - 如何在 Python 中创建可以使用 PIP 安装的 CLI?
- events - 将事件对象从触发函数传递到另一个函数
- python - 美术馆安装Python脚本间歇性锁定,移除热像仪传感器读取功能似乎有效?
- sqlite - sqlite3.OperationalError:靠近“[Total Babies]”:语法错误
- javascript - Angular 的 FormArray 什么时候是传统数组,什么时候是 FormArray 对象?
- c - 我想在 notepad++ 中编译 c 代码,但我无法设置 nppexec
- c# - 基于需要添加到列表的 POCO 添加到现有模型
- python - 允许用户查看他们播放特定曲目的次数的 Django 对象