【发布时间】:2020-12-19 17:00:03
【问题描述】:
这是我的第一个反应应用程序,我不明白出了什么问题。我正在尝试显示页面,但标题中出现两次错误(在第 26:5 行 - fetch(url, { 是和 39:9 我有 setisLoaded(true), setArticles(result.articles);) 行。我将代码从 App 类组件来回更改为功能组件,但没有运气(尽管获取数据有效/有效)。我尝试将所有代码包含在 useEffect 中() 方法变成一个返回语句,只是为了有各种我无法修复的解析错误。所以这里是代码:
import React, { Fragment, useState, useEffect } from 'react';
import Title from './components/Title/Title';
import Content from './components/Content/Content';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Card, Navbar, Form, FormControl, Button } from 'react-bootstrap';
const App = (props) => {
const [error, setError] = useState(null);
const [isLoaded, setisLoaded] = useState(false);
const [articles, setArticles] = useState([]);
const [country, setCountry] = useState('gb');
const handleSubmit = (event) => {
event.preventDefault();
changeCountryHandler();
};
const changeCountryHandler = (event) => {
setCountry(event.target.value);
};
useEffect(() => {
let url =
'https://cors-anywhere.herokuapp.com/http://newsapi.org/v2/top-headlines?country='
+
country;
fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-type': 'application/json',
'x-api-key': 'myApiKey',
SameSite: 'None',
},
})
.then((res) => res.json())
.then((result) => {
setisLoaded(true), setArticles(result.articles);
}),
(error) => {
setisLoaded(true);
setError(error);
};
});
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<Navbar className="bg-secondary justify-content-between" variant="dark">
<p>The selected country is:{country}</p>
<Form inline onSubmit={handleSubmit}>
<FormControl
type="text"
placeholder="Search by country"
className=" mr-sm-2"
onChange={changeCountryHandler}
value={country}
/>
<Button type="submit">Submit</Button>
</Form>
</Navbar>
{articles.map((article) => (
<Card
style={{ width: '100%', height: 'auto' }}
key={article.title}
className="mb-5 mt-4 bg-light"
>
<Card.Img
variant="top"
src={article.urlToImage}
className="pr-3 pl-3"
alt=""
/>
<Card.Body>
<Card.Title>
{article.author} | {article.publishedAt}
<Title title={article.title}>{article.title}</Title>
</Card.Title>
Description: {article.description}
<Content content={article.content}>{article.content}</Content>
Read the full article on{' '}
<Card.Link
href={article.url}
target="_blank"
rel="noopener noreferrer"
>
{article.url}
</Card.Link>
</Card.Body>
</Card>
))}
</>
);
}
};
export default App;
最初,我希望能够根据从表单提交的内容更改 URL 中的国家/地区参数,以便从 API 中获取所需的内容(我知道我应该有一个带有选项而不是输入类型的选择文本,但我现在只是对此进行测试)。但是在这一点上,如果我能够显示任何页面,我会很高兴,因为对此问题的其他响应(添加返回到 useEffect()箭头函数,用括号而不是花括号括起来的语句)对我不起作用,我不明白这个错误。任何想法将不胜感激。
【问题讨论】:
标签: javascript reactjs use-effect