如何在提交时存储状态值

问题描述 投票:0回答:1

我正在尝试在提交时将一个状态属性的值存储在另一个状态属性中,以便可以将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();
};

有人可以指出正确的方向或告诉我我做错了什么吗?

reactjs google-cloud-firestore setstate
1个回答
0
投票

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();
})
© www.soinside.com 2019 - 2024. All rights reserved.