我已成功让我的 React 应用程序显示 Reddit 文章的标题,但图像未显示。
有什么想法我哪里出错了吗?这是我的代码:
App.js
import './App.css';
import { useState, useEffect } from 'react';
import NavBar from './components/NavBar/NavBar';
import Card from './components/Card/Card';
function App() {
//default values of useState() hooks are an array and hot
//useState is an empty array
const [articles, setArticles] = useState([]);
const [subreddit, setSubreddit] = useState("popular");
//every time subreddit changes, useEffect() will recall
useEffect(() => {
fetch("https://www.reddit.com/r/popular.json?limit=10").then(response => {
if (response.status !== 200) {
console.log("Error!")
//return out of the function
return;
}
//parse the response from the server through JSON
//this returns a promise so we have to call .then()
response.json().then(data => {
if (data !== null) {
//setting articles equal to the array of children
setArticles(data.data.children);
//console.log(data.data.children);
}
});
})
//every time, subreddit changes, the useEffect() hook will recall
}, [subreddit]);
return (
<div className="app">
<header>
<div className="nav-bar-container">
<NavBar/>
</div>
</header>
<div className="articles">
{/*Looping through the articles: if articles is not equal null, map through the articles array and get the article
and index of the article. We then get the article which has a key of index.
Then we pass through the data of each article as a prop*/}
{
(articles !== null) ? articles.map((article, index) => <Card key={index} article={article.data}/>) : ''
}
</div>
</div>
);
}
export default App;
Card.js
import "./Card.css";
//pass through props to get our titles
const Card = (props) => {
return (
<article className="reddit-post">
{/*Accessing title and image of post */}
<h3>{props.article.title}</h3>
<div className="image">
{props.article.preview ? <img src={props.article.preview.images[0].source.url}/> : null}
</div>
</article>
)
}
export default Card;
我在页面上看到的内容:
我尝试在此处添加 getUrl() 函数,但不确定如何将其连接到我的应用程序。这对我来说还是很新鲜的。任何帮助将不胜感激!
当我尝试直接访问预览网址时
例如:
https://preview.redd.it/fi3fdlpxyw4d1.jpeg?width=960&crop=smart&auto=webp&s=2e7d775f4333b74fd2f89a2c5fc50373aa4fef38
我看到 reddit 正在发送
403 Forbidden
响应,基本上 Reddit 可能会阻止访问预览网址。
相反,您可以尝试使用
url
或 thumbnail
属性,例如
props.article.thumbnail
或props.article.url
,他们似乎加载图像没有访问问题。
我正在尝试创建一个反应应用程序来尝试在大学的事情。我尝试弄清楚如何使用 reddit api,并按照 reddit 指南获取了-秘密-,但我不知道如何进行 oauth 步骤等。您是否完成了所有这些步骤?