我是个新手,对Reaction和Java脚本很陌生,正在try 访问一个公共API.我有以下功能:
import { useState } from "react";
import CountrySWR from "./CountrySWR";
export default function SearchForm(){
const [countryName, setCountryName] = useState("a");
function handleSubmit(e) {
e.preventDefault();
const query = e.target("query");
setCountryName(query);
}
return (
<>
<form onSubmit={handleSubmit}>
<input name="query"/>
<button type="submit">Search</button>
</form>
<CountrySWR name={countryName}/>
</>
);
};
并且CountrySWR.js如下所示:
import useSWR from "swr";
import { useState } from "react";
const fetcher = (...args) => fetch(...args).then((res) => res.json());
export default function CountrySWR({name}){
const url = "https://restcountries.com/v3.1/name/" + name;
const {
data : countries,
error,
isLoading,
} = useSWR(url, fetcher);
if(error) return <div className="failure">Failed to load data</div>;
if(isLoading) return <div className="loading">Loading, please wait...</div>
if(length > 1){
txt = 'Territories in ' + name;
}
return(
<div style={{ columnns: "150px 6", padding: "10px", margin: '20px', width: 'fit-content'}}>
<h2>{txt}</h2>
{countries &&
countries.map((country, index) => (
<div key={index} style={{margin: '20px', border:"1px solid gray", padding: '20px',
borderRadius: '10px', display: 'inline-block'}}>
<h4>{country.name.common}</h4>
<p>Population: {country.population.toLocaleString('en-US')}</p>
{country.name.special !== null ? <p>{country.name.special}</p> : <p>{country.name}</p>}
<img key={index} src={country.flags.png}
alt="flag" height={150}
style={{margin: '10px',border: '1px solid gray'}}/>
</div>
))}
</div>
);
}
我在App.js中是这样调用的:
<>
...
<SearchForm />
</>
页面最初加载时可以显示CountrySWG元素列表,然后当我单击Search按钮时,我得到以下错误:
Uncaught TypeError: e.target is not a function
at handleSubmit (SearchForm.js:13:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1).....
我需要做些什么才能在我按下搜索按钮时更新<;CountrySWG?