簡體   English   中英

使用 fetch 調用函數從另一個頁面返回結果值,React native

[英]Return the result value with fetch call function from another page, React native

我需要從執行 fetch 調用的 react native 中的另一個頁面返回函數的結果。 我使用的方法如下。 據我所知,這是因為異步調用。 有沒有一種特殊的方法可以在 react native 中實現這一點?

獲取調用.js

import address from '../actions/address'
const dashboard = {
  getvals(){

    return fetch(address.dashboardStats(),
    {method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify( {...
      }),
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.warn(responseData);
      return responseData;

    })
    .catch((error) => { console.warn(error); })
    .done();
    // return 'test_val'';
  }
}

export default dashboard;

儀表板.js

import dashboard from '../../services/dashboard';
class Dashboard extends Component {


  componentDidMount(){
      console.warn(dashboard.getvals());
  }

}

export default connect(mapStateToProps, bindAction)(Dashboard);

它將結果顯示為“未定義”,但該 fetch 調用有效並顯示結果。 有什么建議嗎?

fetchcall.js 中,您將返回一個 Promise。 此外,由於您在.then()方法本身中返回responseData ,因此您不需要.done()方法。

由於getvals()返回一個 Promise,您需要在.then()方法中訪問它的值。

總的來說,你的代碼應該是這樣的:

 function getvals(){ return fetch('https://jsonplaceholder.typicode.com/posts', { method: "GET", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); return responseData; }) .catch(error => console.warn(error)); } getvals().then(response => console.log(response));

我認為最好的架構模式是使用回調函數,通常是作為匿名函數寫入。

///Component.js
my_service.login((data=>{
  this.setState({body: data.body});
}));

////Service.js
export  const login = function (cb){
  fetch('http://myapi.com/103?_format=hal_json')
    .then((response) =>{
      return response.json();
    })
    .then((data) =>{
      cb(data);
    });
}

我仍然是初級開發人員,但經常使用這種模式。 如果有人有理由采用不同的方法,我很樂意聽到。

fetch 總是返回一個 Promise 與您返回的內容無關。 所以你可以返回一個字符串、變量或其他東西,但你必須使用.then來訪問數據

您發出獲取請求的文件

export const graphql = () => {
  return fetch("https://graphqlzero.almansi.me/api", {
    "method": "POST",
    "headers": { "content-type": "application/json" },
    "body": JSON.stringify({
      query: `{
      user(id: 1) {
        id
        name
      }
    }`
    })
  })
    .then((res) => res.json()).then((responseData) => {
      console.log(responseData);
      return responseData;
    })


}

調用函數的文件

 graphql()
 .then((e) => {
     console.log("data", e)
  });

暫無
暫無

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

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