我正在尝试使用Express将数据从外部api动态呈现到React应用。
我的react组件的状态控制着要从api提取哪个页面。
我要实现的是,当我单击“加载更多”按钮时,组件发送以表示下一页编号,然后发送回数据。
这是我尝试过的,但是没有成功:
快递:
const express = require('express');
const fetch = require('node-fetch');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/products', (req, res) => {
const page = req.query.pages;
let url = `https://frontend-intern-challenge-api.iurykrieger.now.sh/products?page=${page}`;
fetch(url).then((response) => response.json()).then((contents) =>
res.send({
products: contents.products,
nextPage: contents.nextPage
})
);
});
app.listen(process.env.PORT || 8080);
反应成分:
import React, { useEffect, useState } from 'react';
import fetch from 'node-fetch';
const Products = () => {
const [ products, setProducts ] = useState([]);
const [ page, setPage ] = useState(1);
const loadProduct = () => {
setPage(page + 1);
};
useEffect(() => {
fetch(`http://localhost:3000/products?pages=${page}`).then((response) => response.json()).then((contents) => {
setProducts([ ...products, ...contents.products ]);
});
}, []);
return (
<div>
{products.map((product) => <p>{product.name}</p>)}
<button type="submit" onClick={loadProduct}>
Load More
</button>
</div>
);
};
export default Products;