我刚接触React和JavaScript,正在尝试访问一个公共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">搜索</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">数据加载失败</div>;
if(isLoading) return <div className="loading">加载中,请稍候...</div>
if(length > 1){
txt = 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>人口: {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="国旗" height={150}
style={{margin: '10px',border: '1px solid gray'}}/>
</div>
))}
</div>
);
}
我在App.js
中这样调用它:
<>
...
<SearchForm />
</>
页面最初加载时显示了一列CountrySWR
元素,但当我点击搜索按钮后,出现以下错误:
Uncaught TypeError: e.target is not a function
at handleSubmit (SearchForm.js:13:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1).....
我需要做什么来修复这个问题,以便在按下搜索按钮时更新<CountrySWR>
?