我正在将表单中的数据发布到我的 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/