亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在反應應用程序的函數調用中使用時,Axios post 不返回數據

在反應應用程序的函數調用中使用時,Axios post 不返回數據

胡說叔叔 2022-10-27 15:08:55
我在我的反應應用程序中使用 axios 發布請求。發布請求工作正常,我在控制臺日志中獲得響應數據。但我想返回該數據以在網頁中呈現。任何幫助是極大的贊賞。謝謝你。這是我發出 axios 請求的函數。function _toRoomName(title) {const axios = require('axios');axios({              method: "POST",               url:"hashroomname.php",              data: {                roomname: title              }           }).then((response) => {                console.log(response.data);                return response.data;          }).catch((error) => {               return error;           });}這是我的渲染方法,需要渲染返回的響應。<Text className = 'titled'>    { _toRoomName(title) } //I want result here </Text>
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

您在return函數調用中缺少 a - 您是從內部then而不是外部承諾返回


function _toRoomName(title) {

    return axios({

              method: "POST", 

              url:"hashroomname.php",

              data: {

                roomname: title 

             }

           }).then((response) => {

                console.log(response.data);

                return response.data;

          }).catch((error) => { 

              return error;

           });

}

但這不會真正起作用。您不能將承諾嵌入到 中<Text>,您需要將其提升到外部狀態


例如


const [ data, setData ] = useState(null)


useEffect(() => {

   _toRoomName(title)

     .then(response => {

       setData(response)

     })

}, [])


return (

  <Text className = 'titled'>

    {data}

  </Text>

)

nowdata在加載<Text>之前為空,在有數據之前為空


查看完整回答
反對 回復 2022-10-27
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

解決方案是:1)使您的功能異步。


async function _toRoomName(title) {

          const axios = require('axios');

            axios({

                  method: "POST", 

                  url:"hashroomname.php",

                  data: {

                    roomname: title 

                 }

               }).then((response) => {

                    console.log(response.data);

                    return response.data;

              }).catch((error) => { 

                  return error;

               });

    }

2)將您的函數移動到 componentDidMount() 并將結果存儲在狀態中。在渲染方法中使用該狀態。


componentDidMount() {

const axios = require('axios');

axios({

              method: "POST", 

              url:"hashroomname.php",

              data: {

                roomname: title 

             }

           }).then((response) => {

                this.setState({state:response.data})

                

          }).catch((error) => { 

              return error;

           });

}


查看完整回答
反對 回復 2022-10-27
  • 2 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號