调用 this.setState 后状态没有改变 [英] State not changing after calling this.setState

查看:78
本文介绍了调用 this.setState 后状态没有改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的表单组件获取数据并尝试使用这些数据设置我的应用组件的状态.

I am getting the data from my form component and trying to set the state of my app component with this data.

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

However, the state.data is an empty object and is not updating the data. I console log the model data before setting it to check if it exists. Their is data within the model.

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;

推荐答案

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

setState() is an async call in React. So you won't likely get the updated state value in the next line. To check the updated value on successful state update, you could check in the callback handler.

改变这个

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

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

这篇关于调用 this.setState 后状态没有改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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