【发布时间】:2020-02-25 10:19:19
【问题描述】:
我正在对 nodejs 服务器进行简单的 axios 调用,以响应从 mongoose 模式模型中获取产品。当我第一次加载页面时,我使用 componentDidMount 从 MongoDB 获取现有产品。但是,当我刷新页面时,所有项目都消失了。
反应组件(componentDidMount):
class Product extends Component {
constructor(props) {
super(props);
this.state = { products: '' };
}
componentDidMount() {
axios.get('http://localhost:3001/getProduct')
.then(res => {
this.setState({ products: res.data });
}).catch((err) => {
console.log(err);
});
}
Nodejs 服务器(/getProduct api):
app.get('/getProduct', (req,res) => {
Products.find(product_id), (err, products) => {
if(err) throw err;
res.status(200).send(products);
});
}
我相信这与回调有关?请帮忙,我是新手。
【问题讨论】:
-
您是在 componentDidMount 中创建组件吗?
-
对不起;错字。固定
-
@jche 如果你想永久保存,那么可以使用 localstorage 或 sessionStorage 因为每次重新加载页面后都会调用 api。
-
对不起,我的意思是刷新页面,而不是重新加载。
-
这是从 localStorage stackoverflow.com/a/58620458/6544460 保存和获取数据的正确方法。
标签: node.js reactjs callback axios react-component