簡體   English   中英

狀態更改時從狀態變量更新數據庫

[英]Update database from state variable when state changes

我要執行的操作是在按下保存按鈕時使用狀態變量更新數據庫。 在保存處理程序中,將一個新值添加到this.state.saved列表中,並調用updataDatabase函數。 問題在於,當按下按鈕時,setState不會更新狀態變量,因此數據庫中沒有任何更新。 我的問題是:如何使setState更新組件,以便更新數據庫? 這是我的代碼

class Articles extends Component{
    constructor(props){
        super(props);
        this.state = {
            check:false,
            saved:[]
        }

        this.handleSave = this.handleSave.bind(this)
    }

    async componentDidMount(){
        savedArticles = this.props.article.saved

        this.setState({
            check:this.props.article.check,
            saved:this.props.article.saved
    })
}

async updateDataBase(){
    let updates = {
        body:{
            userName:this.props.article.user,
            userEmail:this.props.article.email,
            userPhone:this.props.article.phone,
            savedArticles:this.state.saved,
            userInterests:this.props.article.interestList,

        }


    }
    console.log(updates)

    return await API.put(apiName,path,updates);
}

handleSave () {
    const urlList = [];
    let article = {};

    for(let i=0; i<this.state.saved.length; i++){
        urlList.push(this.state.saved[i].url)
    }
    if(!urlList.includes(this.props.article.url)){

        article =  {
            url:this.props.article.url,
            title:this.props.article.title,
            image:this.props.article.urlToImage,
            author:this.props.article.author,
            check:true,

        }
        savedArticles.push(article)
            this.setState({
                check: true,
                saved:[...this.state.saved,article]

            })


        this.updateDataBase();

    }
}

render()
{
    console.log(this.state.check)

    return (
        <div className="item">
            <div className="card">
                <img src={this.props.article.urlToImage} alt="No available image" width="100%" height="200px"></img>
                <div>

                    <h5 className="card-title">{this.props.article.title}</h5>
                    <p className="card-text">{this.props.article.author}</p>
                    <a href={this.props.article.url} target="_blank" id="articleLink" className="btn btn-primary"><FontAwesomeIcon icon="external-link-alt" /> See full article</a>

                    {this.state.check?(
                        <button disabled={true}  id="buttonsArticle" className="btn btn-primary"><FontAwesomeIcon icon="check" /> Saved</button>
                    ):(
                        <button onClick={this.handleSave.bind(this)} id="buttonsArticle" className="btn btn-primary"><FontAwesomeIcon icon="save" /> Save Article</button>
                    )}

                </div>
            </div>
            <div className="divider"></div>
        </div>

    )
}}

那里的問題是您的代碼正在同步運行。 您正在設置狀態,然后調用this.updateDataBase(); 但狀態在這種情況下不會更新。 此后實際發生狀態更新和后續渲染。 您可以想象它像調用setState的隊列一樣工作,它注意到狀態將需要更新,但是隊列中緊接的所有其他事物都必須首先執行。

看一下這個: https : //codesandbox.io/s/32n06zlqop?fontsize=14如果單擊該按鈕,它將立即注銷為false的狀態,然后再次在componentDidUpdate注銷,您會看到狀態已設定。

因此,您有兩種選擇,可以在componentDidUpdate生命周期方法內調用更新數據庫函數。 每次渲染后都會調用此函數,可以通過狀態更改來觸發該渲染。

或者,您可以傳遞第二個回調函數參數來設置狀態,在實際設置狀態后調用該參數。 這可能是最優雅的版本:

this.setState({
      check: true,
      saved:[...this.state.saved, article]
    }, this.updateDataBase)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM