反应状态变化无法按预期进行

时间:2018-10-10 22:53:21

标签: reactjs

嗨,这是我尝试从表单提交数据的代码。

import * as React from 'react'

export class User extends React.Component{

    constructor(props) {
        super(props);

        this.state = {
            name: '',
            message: '',
            messages: ''
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }
    render() {
        return (

            <div class="panel panel-default" id="frame1" onSubmit={this.handleSubmit}>

            <form class="form-horizontal" action="/action_page.php">
                <div class="form-group">
                    <label class="control-label col-sm-2" for="name">Your Name </label>
                  <div class="col-sm-10">
                            <input type="text" class="form-control" name="name" placeholder="Enter your Name"  onChange={this.handleChange} />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2" for="message">Message</label>
                    <div class="col-sm-10">
                            <input type="text" class="form-control"  name="message" placeholder="Enter your Message" onChange={this.handleChange}/>
                    </div>
                </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" id="submit" class="btn btn-default">Submit</button>
                        </div>
                    </div>
                </form>
                </div>
       );
    }

    handleChange(evt) {
        this.setState({ [evt.target.name]: evt.target.value });
    }


    handleSubmit(event) {
        this.setState({ messages: this.state.message });
        alert('A name was submitted: ' + this.state.name + ' jjjjjj' + this.state.messages);
        event.preventDefault();
    }
}

您可以在handleSubmit(event)方法中看到,我正在将message的值设置为messages。但是,当我尝试打印消息时,没有设置任何值。我在这里做错了什么。不需要打印该值

1 个答案:

答案 0 :(得分:1)

setState是异步的。试试这个:

handleSubmit(event) {
    event.preventDefault();
    this.setState({ messages: this.state.message }, () => {
        alert('A name was submitted: ' + this.state.name + ' jjjjjj' + this.state.messages);
    });
}
  

setState()并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用this.state之后立即阅读setState()是一个潜在的陷阱。相反,请使用componentDidUpdatesetState回调(setState(updater, callback)),可以保证在应用此更新后都会触发其中的一种。

https://reactjs.org/docs/react-component.html#setstate