React.js调用Node.js爬虫API获取数据并渲染到列表的方法咨询
前置配置确认
首先保证Node.js侧的接口符合以下要求:
- 接口返回JSON格式数组,每一项结构为
{"title": "通知标题", "url": "跳转链接"} - 配置跨域支持:先安装cors依赖
npm install cors,在Node服务入口文件添加如下代码:
const cors = require('cors') app.use(cors())
核心修改方案
你只需修改NoticesList.js组件即可同时解决请求接口和数据渲染两个问题,修改后完整代码如下:
import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import NoticesItem from './NoticesItem'; const NoticesListBlock = styled.div` box-sizing: border-box; padding-bottom: 3rem; width: 768px; margin: 0 auto; margin-top: 2rem; font-size: 16px; /* 修正字号,避免继承父级45px的超大字体 */ `; const NoticesList = () => { // 存储接口返回的文章列表 const [articles, setArticles] = useState([]); // 可选:加载、错误状态提示 const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // 组件挂载时请求Node接口,替换成你自己的实际接口地址 const fetchNotices = async () => { try { const res = await fetch('http://你的Node服务地址/api/你配置的接口路径'); if (!res.ok) throw new Error('接口请求异常'); const data = await res.json(); setArticles(data); setLoading(false); } catch (err) { setError(err.message); setLoading(false); } }; fetchNotices(); }, []); if (loading) return <NoticesListBlock>加载中...</NoticesListBlock>; if (error) return <NoticesListBlock>加载失败:{error}</NoticesListBlock>; return ( <NoticesListBlock> {/* 遍历数组渲染列表项,key用唯一的url即可 */} {articles.map((item, index) => ( <NoticesItem key={item.url || index} article={item} /> ))} </NoticesListBlock> ); }; export default NoticesList;
如果习惯用axios发起请求,先安装依赖npm install axios,将上述fetch请求部分替换为对应axios写法即可。
内容的提问来源于stack exchange,提问作者박종준
相关产品推荐
相关产品推荐

