反应动态改变状态列表异步问题

时间:2018-09-07 22:18:51

标签: reactjs asynchronous state

我对React还是很陌生,我目前正试图多次将状态追加到列表中。但是,状态似乎没有更新,我怀疑这可能是由于async(?)引起的。我将不胜感激任何指针:-)

from sqlalchemy.orm import relationship, sessionmaker, session
from sqlalchemy.types import Integer, Float, String
from sqlalchemy import types, create_engine, inspect, MetaData, Table, Column, ForeignKey, ForeignKeyConstraint, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base

postgres_dbpostgres  = {'drivername': 'postgresql',
           'username': 'username',
           'password': 'password',
           'host': 'hosting_bits',
           'port': 5432,
           'database': '_db'}

PSQLengine = create_engine(URL(**postgres_dbpostgres), echo=True)

class Table_A(Base):
    __tablename__ = 'table_name_a'
    table_a_id = Column(Integer, index=True,unique=True,primary_key=True)
    important_value_a = Column(String(10), index=True, unique=True, nullable=False, primary_key=True)
    foo = Column(String(240))
    bar_float = Column(Float(precision=53, asdescimal=True))

class Table_B(Base):
    __tablename__ = 'table_name_b'
    table_b_id = Column(Integer, index=True, unique=True)
    table_b_uuid = Column(UUID(as_uuid=True), index=True, nullable=False, primary_key=True)
    important_value_a = Column(String(10),ForeignKey('table_name_a.important_value_a'),nullable=False)
    important_value_b = Column(String(10))
    important_value_c = Column(String(10))

class TemplateTable(object):
    __tablename__ = 'important_value_a'
    new_table_id = Column(Integer, primary_key=True)  
    important_value_b = Column(String(10))
    important_value_c = Column(String(10))

Base.metadata.create_all(PSQLengine)

上面的代码显示:

this.state = {
    data: []
};

var json = {name: "default", cost:1}

for (var i = 0; i < 3; i++) {
        this.setState({ data: [...this.state.data,json] });
    }

编辑:更多代码

[]  
[]
[{name: "default", cost: 1}]

2 个答案:

答案 0 :(得分:2)

您应该使用this.setState()的功能形式。

this.state = {
    data: []
};

var json = {name: "default", cost:1}

for (var i = 0; i < 3; i++) {
    this.setState(prevState => ({ data: [...prevState.data,json] }));
}

此处有更多信息:https://reactjs.org/docs/react-component.html#setstate

答案 1 :(得分:1)

setState()是异步的,因此不能保证在下次调用setState()时将其更新。

我将更改您的代码以首先使用数据创建数组,然后在完成时调用setState()。看起来像这样:

componentWillMount() {
    var data = [];
    for (var i = 0; i < 3; i++) {
        data.push(this.getValue(this.props.data[i]));
    }
    this.setState({data});
}

getValue(rowData) {
    let {
        checkbox: checkbox,
        checked: checked,
        data: data,
        name: name,
        headers: headers
    } = this.props;
    var json = {};
    for (var i = 0; i < headers.length; i++) {
        json[headers[i]] = rowData[i];
    }
    json["checked"] = checked;
    return json;
}