简体   繁体   English

使用Reactjs单击显示按钮时如何渲染滤过国家?

[英]How to render filitered countries when clicking the show button using Reactjs?

I am new to reactjs. 我是Reactjs的新手。 I am trying to implement a search filter for countries from this Json server using axios.get() . 我正在尝试使用axios.get()从此Json服务器为国家/地区实现搜索过滤器。 If the filter array contains only 1 country then my application works fine otherwise if the filter array contains more than 1 but less than 10 countries I want to output this result. 如果筛选器数组仅包含1个国家/地区,则我的应用程序运行正常,否则,如果筛选器数组包含1个以上但少于10个国家/地区, 我想输出此结果。 I am able to successfully achieve the filter part on my browser but when I click on "show" button it only outputs on the console. 我能够在浏览器上成功实现过滤器部分,但是当我单击“显示”按钮时,它仅在控制台上输出。

Here's my code : 这是我的代码:

const ShowBetween1to10 = ({country, buttonHandler}) => {
  return(
    <div key={country.alpha2Code}>
      <p>
        {country.name}
        <button onClick = {buttonHandler}>show</button>
      </p>
    </div>
  )

}

const App = () => {
  const [countries,setCountries] = useState([])
  const [filter,setFilter] = useState('')
  //const [flag, setFlag] = useState('')

  useEffect(() =>{
    axios.get('https://restcountries.eu/rest/v2/all')
    .then(response => setCountries(response.data))
  }, [])

  //console.log('countries[] = ',countries)

  const buttonHandlerOf = (alpha2Code) => {
    const url = `https://restcountries.eu/rest/v2/alpha/${alpha2Code}`

    return (axios.get(url).then(response =>{
      console.log(response.data)
      console.log(response.data.languages)
      return(
        <div>
          {view(response.data)}
        </div>
      )})
    )
  }

  const view = (country) =>{
    //console.log(country.languages)
    const lang = country.languages.map(lang => lang.name)
    console.log(lang)
    return(
      <div>
            <h1>{country.name}</h1>
            <h2>languages</h2>
            <ul>{printLanguages(lang)}</ul>
            <img src={country.flag}  alt="flag photo" height="100" width="100"/>
      </div>
    ) 
  }
  const rows = () => {
    const len = countriesToShow.length 
    if(len > 10){
      return(<p>Too many matches, specify another filter</p>)
    }
    else if(len >=1 && len <= 10){
      if(len === 1){
        const country = countriesToShow[0];
        return(
          <div>
            {view(country)}
          </div>
        )
      }
      else{
        return(countriesToShow.map(country => 
          <ShowBetween1to10 
           key ={country.alpha2Code}
           country = {country}
           buttonHandler = {() => buttonHandlerOf(country.alpha2Code)}
          />  
        ))
      }

    }


  }
  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }
  const countriesToShow = filter === '' ? [] : countries.filter(country =>  {
    return country.name.toLowerCase().includes(filter.toLowerCase())
  })
  return(
    <div>
      find countries
      <input value={filter} onChange={handleFilterChange} />
      {rows()}
    </div>
  )
}

export default App;`

If anybody can help me I'll be grateful of you. 如果有人可以帮助我,我将感激您。 Start looking from the else if(len >1 && len <10) part of rows() function and please explain why view() is not rendering on the browser but only on the console ? rows()函数的else if(len >1 && len <10)部分开始查找,请解释为什么view()不在浏览器上呈现,而仅在控制台上呈现? Thanks a heap !!! 谢谢一大堆!

Your buttonHandlerOf is incorrect. 您的buttonHandlerOf不正确。 You can't render a view from it. 您无法从中渲染视图。 Generally you'd need to set the response data to state, which would be then rendered. 通常,您需要将响应数据设置为state,然后将其呈现。

Also I'd recommend you to make those view functions that return JSX into separate React components. 我也建议您制作那些将JSX返回到单独的React组件的视图函数。

 const buttonHandlerOf = alpha2Code => {
    const url = `https://restcountries.eu/rest/v2/alpha/${alpha2Code}`;

    return axios.get(url).then(response => {
      console.log(response.data);
      console.log(response.data.languages);
      setCountries([response.data]) // set the country to the state here
    });
  };

As pointed in the comments, this would remove all other countries, so you could fetch them again when the filter is cleared: 正如评论中指出的那样,这将删除所有其他国家/地区,因此您可以在清除过滤器后再次获取它们:

 useEffect(() => {
    if (!filter) {
      axios
        .get("https://restcountries.eu/rest/v2/all")
        .then(response => setCountries(response.data));
    }
  }, [filter]);

Alternatively you could add a reset button. 或者,您可以添加一个重置按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM