簡體   English   中英

React-如何從獲取POST獲取異步數據

[英]React - how to get async data from fetch POST

我正在將數據從表單發布到我的json服務器url localhost:3000 / recipes中,並且試圖在不刷新頁面的情況下獲取其他組件中的數據。 我將一些數據發布到配方url,當我返回頁面上的其他hashURL時,我需要刷新頁面以獲得結果。 有什么方法可以使生命周期或類似情況中的數據異步?

componentDidMount() {
    recipesService.then(data => {
      this.setState({
        recipes: data
      });
    });
  }

配方服務

const url = "http://localhost:3000/recipes";
let recipesService = fetch(url).then(resp => resp.json());
let sendRecipe = obj => {
  fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(obj)
  })
    .then(resp => resp.json())
    .then(data => console.log(data))
    .catch(err => console.log(err));
};

module.exports = {
  recipesService,
  sendRecipe
};

可能您想使用Redux之類的東西。 :)

或者,您可以為此組件創建緩存:

// cache.js
let value;
export default {
  set(v) { value = v; },
  restore() { return value; },
};

// Component.js
import cache from './cache';
...
async componentDidMount() {
  let recipes = cache.restore();
  if (!recipes) {
    recipes = await recipesService;
    cache.set(recipes);
  }
  this.setState({ recipes });
}

暫無
暫無

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

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