Javascript React-如何从fetch POST获取异步数据
我正在将表单中的数据发布到我的json服务器url localhost:3000/recipes,并且我正在尝试在其他组件中获取数据,而不刷新页面。我将一些数据发布到recipes url,当我返回到页面上的其他hashURL时,我需要刷新页面以获得结果。有没有办法从生命周期或类似的东西中异步获取数据Javascript React-如何从fetch POST获取异步数据,javascript,json,reactjs,Javascript,Json,Reactjs,我正在将表单中的数据发布到我的json服务器url localhost:3000/recipes,并且我正在尝试在其他组件中获取数据,而不刷新页面。我将一些数据发布到recipes url,当我返回到页面上的其他hashURL时,我需要刷新页面以获得结果。有没有办法从生命周期或类似的东西中异步获取数据 componentDidMount() { recipesService.then(data => { this.setState({ recipes:
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 });
}
可能您想使用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 });
}
Redux可能是正确的方法,或者如果它只是一个子组件,您可以将其作为道具传递进来。非常感谢!我将在我的应用程序中教授如何实现redux:)redux可能是正确的方法,或者如果它只是一个子组件,您可以将其作为道具传递进来。非常感谢!我将教授如何在我的应用程序中实现redux:)