javascript - React - 如何从 fetch POST 获取异步数据

标签 javascript json reactjs

我正在将表单中的数据发布到我的 json-server url localhost:3000/recipes,并且我试图在不刷新页面的情况下获取其他组件中的数据。我正在将一些数据发布到菜谱网址,当我返回页面上的其他 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 });
}

关于javascript - React - 如何从 fetch POST 获取异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52765853/

相关文章:

javascript - 无法从 json 对象添加键值对到 json 对象中

reactjs - react : ref is not a prop

javascript - Array.sort() 比较函数返回未定义

javascript - 如何使用 Node.js createReadStream 和 createWriteStream 写入多个文件

json - 拿到Alamofire的返回数据后下一步该怎么办?

jQuery - 加载后显示列表

javascript - 如何使用模拟 api 调用测试 React 组件

javascript - React 在构造函数上向服务器发送请求以获取设置列表

javascript - 快线功能未提升

javascript - 使用 URL.Document 或 window.location.href 时大括号转换为十六进制