当我点击搜索按钮时如何更新反应组件?

问题描述 投票:0回答:1

我是 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">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 元素列表,然后当我单击“搜索”按钮时,出现以下错误:

Uncaught TypeError: e.target is not a function
    at handleSubmit (SearchForm.js:13:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1).....

我需要做什么来解决这个问题,以便

推荐的方法是使用状态变量控制输入。

  const [query, setQuery] = useState(''); // Declare a state variable...
  // ...
  return (
    <input
      value={query} // ...force the input's value to match the state variable...
      onChange={e => setQuery(e.target.value)} // ... and update the state variable on any edits
    />
  );

在这种情况下,您可以更新国家/地区以匹配提交时的查询。

javascript reactjs
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.