反应如何存储状态值onSubmit

时间:2020-06-06 19:19:05

标签: reactjs google-cloud-firestore setstate

我试图在提交时将一个状态属性的值存储在另一个状态属性中,以便可以将URL友好的数据段提交到我的数据库。

下面是提交表单时调用的函数的一部分。目前,该表单已提交到数据库(Firestore),并且工作正常。但是,我需要收集用户输入到streetAddress的值,对它进行分段,然后使用状态的slug属性将其作为自己的slug字段提交给我的数据库。

我遇到的问题是我不知道该怎么做。我尝试了几种方法,并且将slug提交到数据库,但始终使用空值。以下是我尝试过的方法。

onSubmit = event => {
const {  reviewTitle, reviewContent, streetAddress, cityOrTown, 
        countyOrRegion, postcode, startDate, endDate, landlordOrAgent, rating, slug } = this.state;

this.setState({
    slug: streetAddress
})


// Creating batch to submit to multiple Firebase collections in one operation
var batch = this.props.firebase.db.batch();
var propertyRef = this.props.firebase.db.collection("property").doc();
var reviewRef = this.props.firebase.db.collection("reviews").doc();

batch.set(propertyRef, { streetAddress, cityOrTown,
    countyOrRegion, postcode, slug,
    uid });
batch.set(reviewRef, { startDate, endDate,
    reviewTitle, reviewContent, rating, 
    uid });
batch.commit().then(() => {
    this.setState({ ...INITIAL_STATE });
    });
    event.preventDefault();
};

有人能指出我正确的方向还是告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

this.setState是一个异步功能。因此,您可以做的就是在状态更新后调用回调函数。

this.setState({
    slug: streetAddress
}, () => {
    // Creating batch to submit to multiple Firebase collections in one operation
    var batch = this.props.firebase.db.batch();
    var propertyRef = this.props.firebase.db.collection("property").doc();
    var reviewRef = this.props.firebase.db.collection("reviews").doc();

    batch.set(propertyRef, {
        streetAddress, cityOrTown,
        countyOrRegion, postcode, slug,
        uid
    });
    batch.set(reviewRef, {
        startDate, endDate,
        reviewTitle, reviewContent, rating,
        uid
    });
    batch.commit().then(() => {
        this.setState({ ...INITIAL_STATE });
    });
    event.preventDefault();
})