【发布时间】:2021-07-14 15:39:20
【问题描述】:
NB:请有人在这里解释如何格式化我的代码,它只是不起作用,我做错了什么。
这是我根据 cmets 重构后的代码,现在可以使用了!
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const App = () => {
const [countries, setCountries] = useState([])
useEffect(() => {
console.log('effect');
axios
.get('https://restcountries.eu/rest/v2/all')
.then(response => {
console.log('promise fulfilled');
const countries = response.data
setCountries(countries)
})
}, [])
const [searchVal, setSearchVal] = useState('')
const searchOnChangeEventHandler = (event) => setSearchVal(event.target.value)
const filteredCountries = (searchVal, countries) => countries.filter(country => country.name.toLowerCase().includes(searchVal.toLowerCase()))
const filteredCountriesLength = filteredCountries(searchVal, countries).length
return (
<div>
<h1>coutries data</h1>
<div>
<input
type='text'
placeholder='search countries'
value={searchVal}
onChange={searchOnChangeEventHandler}
>
</input>
</div>
<div>
<>
{
countries.length
? (searchVal
? (
filteredCountriesLength <= 10 && filteredCountriesLength > 1
? filteredCountries(searchVal, countries).map(country => <p key={country.name}>{country.name}</p>)
: <span>{filteredCountriesLength} matches! too many matches, specify another filter...</span>
)
: <span>type to search..</span>)
: <span>populating countries data...</span>
}
</>
</div>
</div >
)
}
export default App
下面的部分现在按照我想要的方式工作,在我清理代码之后,我认为最好使用 if-else 然后按照建议转换为三进制。
<div>
<>
{
countries.length
? (searchVal
? (
filteredCountriesLength <= 10 && filteredCountriesLength > 1
? filteredCountries(searchVal, countries).map(country => <p key={country.name}>{country.name}</p>)
: <span>{filteredCountriesLength} matches! too many matches, specify another filter...</span>
)
: <span>type to search..</span>)
: <span>populating countries data...</span>
}
</>
</div>
NB:有没有办法去除代码中的所有这些空白?
我想打印type to search whenever the searchVal input was empty。
【问题讨论】:
-
那么您面临的问题是什么?
-
即使你让它以某种方式工作,结果也很难维护。考虑将此部分移动到单独的函数或组件中。
-
通常我只是在普通 if(){} 中做很多 if 语句,然后我将其更改为三元
-
代码格式不正确,我无法格式化
标签: javascript reactjs conditional-statements conditional-operator