簡體   English   中英

從axios響應中反應設置狀態

[英]React setting state from an axios response

我試圖用從axios POST調用返回的信息更新狀態。 我收到一條錯誤消息,提示TypeError: Cannot read property 'setState' of undefined 在我看來, this無法從API響應中使用。

submitData= () => {
        axios.post("url", this.props.data)
        .then(function (result) {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });

    }

我可以控制台記錄result.data.id ,它是正確的ID。 我正在所有客戶端上執行此操作,並且我不想構建服務器或使用reducer。

在您的回調中使用arrow函數,如下所示:

submitData= () => {
        axios.post("url", this.props.data)
        .then((result) => {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });

    }

您還可以使用async / await語法並將數據作為參數傳遞,以提高靈活性/可重用性。 嘗試:

submitData = async (data) => {
    try {
        const result = await axios.post('url', data);
        console.log('Success', result);
        const { id } = result.data;
        this.setState({
            ...this.state,
            id,
        });
    } catch (err) {
        console.log('Failure', err);
    }
}

嘗試將.then設為匿名函數來綁定this

submitData= () => {
    axios.post("url", this.props.data)
    .then((result) => {
        console.log(result,'success');
        this.setState({
            ...this.state,
            id: result.data.id
        })
      })
      .catch((err) => {
        console.log(err, 'fail');
      });
}

在回調函數this將是不確定的(這就是如何this JS中的作品)。 如果您想輕松修復,只需使用箭頭功能

submitData= () => {
        axios.post("url", this.props.data)
        .then(result => {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });
    }

進一步了解this https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

暫無
暫無

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

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