我正在创建一个基本新闻应用程序,作为学习反应的练习。我已经学会了一些创建搜索栏的方法,但我不知道如何正确地实现它们。对于这个项目,我只想允许用户进入搜索栏输入一个国家,并让它更改URL。该国目前在TopHeadlinesUS被称为useFetch。js。有人能帮我弄清楚吗?
useFetch。js
import { useEffect, useState } from "react"; import axios from "axios";
function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
axios
.get(url)
.then((response) => {
setData(response.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setLoading(false);
}); }, [url]);
return { data, loading, error }; } export default useFetch;
头顶线。js
import "../App.css";
import useFetch from "./useFetch";
import { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Row, Col, Container } from "react-bootstrap";
import { FaBeer } from "react-icons/fa";
import { Puff } from "react-loading-icons";
import LoadingScreen from "./LoadingScreen";
import { Link } from "react-router-dom";
const Test = () => {
const [country, setCountry] = useState("us");
const {
data: start,
loading,
error,
} = useFetch(
`https://newsapi.org/v2/top-headlines?country=${country}&apiKey=712a8c0fa12d406c8f710f1d01b47dd8`
);
console.log(start, "after fetch");
if (loading) return <h1>{<LoadingScreen />}</h1>;
if (error) return console.log(error);
const styles = {
cardImage: {
objectFit: "cover",
},
};
return (
<div className="TopHeadlinesUS">
<Container fluid>
{/*Row1*/}
<Row>
<Col>
<Link to={{ pathname: start?.articles[0].url }} target="_blank">
<center>
<img variant="top" src={start?.articles[0].urlToImage} />
</center>
</Link>
<Link to={{ pathname: start?.articles[0].url }} target="_blank">
<h2>{start?.articles[0].title.replace(/-[^,]+$/, "")}</h2>
</Link>
</Col>
<Col>
<Link to={{ pathname: start?.articles[1].url }} target="_blank">
<center>
<img alt="" variant="top" src={start?.articles[1].urlToImage} />
</center>
</Link>
<Link>
<h2>{start?.articles[1].title.split("-")[0]}</h2>
</Link>
</Col>
....