首页 > 解决方案 > 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.

标签: reactjs

解决方案


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?


推荐阅读