调用this.setState后状态不变

Kay*_*Kay 2 reactjs

我从我的表单组件中获取数据,并尝试使用此数据设置我的应用程序组件的状态.

但是,state.data是一个空对象,不会更新数据.我在设置之前控制记录模型数据以检查它是否存在.它们是模型中的数据.

import React, { Component, Fragment } from "react";
import Form from "../components/Form";

import product from "./product.json";

class App extends Component {

    constructor() {
        super();  

        this.state = {
            data: {}
        };

    }

    onSubmit = (model) => {

        console.log("Outer", model);

        this.setState({
            data: model
        });

        console.log("Form: ", this.state);
    }
    render() {

        const fields = product.fields;

        return (
            <Fragment>
                <div>Header</div>
                <Form
                    model={fields}
                    onSubmit={(model) => {this.onSubmit(model);}}
                />
                <div>Footer</div>
            </Fragment>
        );
    }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

Din*_*yan 6

setState()是React中的异步调用.因此,您不可能在下一行中获得更新的状态值.要检查成功状态更新的更新值,您可以检入回调处理程序.

改变这个

onSubmit = (model) => {
  console.log("Outer", model);
  this.setState({
    data: model
  });
  console.log("Form: ", this.state);
}
Run Code Online (Sandbox Code Playgroud)

onSubmit = (model) => {
  console.log("Outer", model);
  this.setState({
    data: model
  }, () => {
    console.log("Form: ", this.state);
  });
}
Run Code Online (Sandbox Code Playgroud)