为什么调用react setState方法不会立即改变状态? [英] Why calling react setState method doesn't mutate the state immediately?

查看:1007
本文介绍了为什么调用react setState方法不会立即改变状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读表单部分class =post-tagtitle =show questions tagged'reactionjs' =tag> reactjs 文档,并尝试使用此代码演示 onChange 用法( JSBIN )。

I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).

var React= require('react');

var ControlledForm= React.createClass({
    getInitialState: function() {
        return {
            value: "initial value"
        };
    },

    handleChange: function(event) {
        console.log(this.state.value);
        this.setState({value: event.target.value});
        console.log(this.state.value);

    },

    render: function() {
        return (
            <input type="text" value={this.state.value} onChange={this.handleChange}/>
        );
    }
});

React.render(
    <ControlledForm/>,
  document.getElementById('mount')
);

当我更新< input /> 浏览器中的值, handleChange 回调中的第二个 console.log 打印相同的 value 作为第一个 console.log ,为什么我看不到 this.setState({value的结果:event.target.value}) handleChange 回调范围内?

When I update the <input/> value in the browser, the second console.log inside the handleChange callback prints the same value as the first console.log, Why I can't see the result of this.setState({value: event.target.value}) in the scope of handleChange callback?

推荐答案

来自React的文档


setState()不会立即改变这个.state 但会创建
挂起状态转换。在调用此
方法后访问 this.state 可能会返回现有值。没有
保证对 setState 的调用进行同步操作,并且可以为了性能提升而调用

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

如果你想在状态发生变化后执行一个函数,请将其作为回调传递。

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
});

这篇关于为什么调用react setState方法不会立即改变状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆