On the trigger of onChange event in react input box

recently encountered some problems in the process of learning react.js. Go to the code diagram first:

clipboard.png

inputonChangestate,stateinputvalue. consolestateinputvalue,...

clipboard.png
state,,,.

clipboard.png
this picture, which obtains the real-time value, fetched by input directly from the event event of the event, does not have this problem.

so I don"t understand why this round of transactions in react should have ended after the execution of setState, the state of the component has been updated, why does it console the value of the previous round? Look forward to the boss"s answer.

ps: aside: why bind state, to the value of input? I think it"s okay not to bind it. Users can enter it normally and just need an onChange event to update state.


setState operates asynchronously. You can't get state's finger right away. You can use callback to get
this.setState ({value: event.target.value}, () = > console.log (this.state.value))


setState does not immediately refresh the state tree, it also merges the old and new states and scans the virtual DOM tree to find the affected nodes (such as value=this.state.value ) and then updates the UI section on the node, which is very time-consuming (relatively speaking), so it will wait for an opportunity to do batch updates, until then state will not be changed.

deeply study the working mechanism of React setState-DanceOnBeat-blog Park

as for why you bind value to state , because react has bi-directional binding , which opens Model and View , you no longer have to listen to whether a variable changes and then make changes on the interface.


setState () is an asynchronous operation. When the following console.log () executes, state has not been updated, so the output is the previous value.


setState, as an asynchronous operation, supports callback.

this.setState({value: event.target.value}, () => console.log(this.state.value))

there is no problem with this. The state you finally submitted must be the same as the one you typed

.
Menu