首页 > 解决方案 > 反应如何在提交上存储状态值

问题描述

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

以下是提交我的表单时调用的函数的一部分。目前,表单提交到数据库(Firestore)并且工作正常。但是,我需要收集用户输入到 streetAddress 的值,对其进行 slugify,然后使用我所在州的 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();
};

谁能指出我正确的方向或告诉我我做错了什么?

标签: reactjsgoogle-cloud-firestoresetstate

解决方案


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();
})

推荐阅读