reactjs - Form input state doesn't show update in developer tools, but logs them. Am I rerendering properly?
问题描述
I am learning about Controlled Forms, and have built a simple one input form, to practice on. It seems that the state of the component is not being updated, when I look at my react developer tools. If I console.log the state, I can see the state has changed with each letter I input, but nothing is changing in the developer tool. I am concerned it may not be rendering properly.
I've built the form, exported and imported into App.js. Everything seems to be wired correctly, including a console.log to display the state with each change.
class Form extends Component {
constructor(props) {
super(props);
this.state = {
username: ''
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(evt) {
this.setState(
{username: evt.target.value},
() => console.log(this.state)
)
}
render() {
return (
<form>
<input
name="username"
value={this.state.username}
onChange={this.handleChange}
/>
</form>
)
}
}
I don't get any errors, but observed 2 interesting things: in react-developer-tools, under the form component, the state stays the same, but a little arrow pops up that says "reset value," and if I click on the App component, then back on the Form, the state is filled with the value.
解决方案
You can check the React documentation:
The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.
So everything is working as expected, if the callback is getting called it's because the component re-rendered.
Are you using the latest version of react developer tools released last month?
推荐阅读
- azure-devops - java.lang.ClassNotFoundException: com.salesforce.ant.DeployTask$CodeNameElement
- firebase - Cloud Functions firebase.json 的 Firebase 托管重写不适用于多个环境
- ios - SwiftUI 结合 NavigationBarBackButton 和标题
- python - tensorflow 音频识别错误“标题不匹配:预期 RIFF 但找到”
- xml - Golang xml unmarshal:如果我们在嵌套结构中使用 Xml 名称元素,则只有根元素会被解组
- unity3d - FileNotFoundException: Temp\gradleOut\build\outputs\bundle\release\gradleOut.aab 不存在
- c - 如果编译器要求程序中给出更多数量的输入,那么程序中是否有任何错误
- azure - 使用 Terraform 将托管身份访问权限分配给应用程序角色
- mysql - MySQL 意外关闭。(XAMPP)
- android - 如何在 android studio 中导入或打开 react-native 项目?