Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

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

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

(我正在阅读文档的Forms部分,只是尝试了这段代码来演示onChange用法( 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')
);

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?

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

  ask by tarrsalah translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From React's documentation :

(从React的文档中 :)

setState() does not immediately mutate this.state but creates a pending state transition.

(setState()不会立即使this.state突变,但会创建一个挂起的状态转换。)

Accessing this.state after calling this method can potentially return the existing value.

(调用此方法后访问this.state可能会返回现有值。)

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

(无法保证对setState的调用的同步操作,并且可能会为提高性能而批量调用。)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...