【发布时间】:2020-07-14 00:03:26
【问题描述】:
我使用 this API 创建了一个 React 应用程序,然后尝试添加搜索功能。一切正常,但有时我无法看到搜索结果。例如,如果您查看this screenshot,您将能够看到我想说的话。另外,我想忽略区分大小写,并希望得到确切的结果,而不管它的大小写。我尝试将搜索词和国家/地区转换为大写,但结果不正确。
App.js:
import React, { Component } from 'react'
import Result from './Result';
import Form from 'react-bootstrap/Form';
export default class App extends Component {
constructor(){
super();
this.state = {
data: [],
searchText:'',
searchResult:[],
isSearch:false
}
this.onSearchChange=this.onSearchChange.bind(this);
// this.fetchSearchResult=this.fetchSearchResult.bind(this);
}
onSearchChange= (e) =>{
console.log("search change "+this.state.searchText)
this.setState({
searchText:e.target.value,
isSearch:!this.state.isSearch
})
console.log("api data"+this.state.data)
}
/* fetchSearchResult= () =>{
console.log(this.state.searchText)
console.log("inside fetch")
let store= this.state.data.map(item=>{
let {country}=item
return(country)
})
console.log(store)
var areEqual = store.includes(this.state.searchText);
console.log(this.state.areEqual)
return (areEqual)?
store:'not matched'
// return store;
} */
componentDidMount() {
const url =
'https://corona.lmao.ninja/countries?sort=country'
fetch(url)
.then(result => result.json())
.then(result => {
this.setState({
data: result,
})
})
}
render() {
return (
<div>
<Form.Group>
<Form.Label>Search</Form.Label>
<Form.Control value={this.state.searchText}onChange={this.onSearchChange} type="text" placeholder="Enter country" />
</Form.Group>
<Result data={this.state.data}
toSearch={this.state.searchText}
searchCheck={this.state.isSearch}
searchValue={this.state.searchText}/>
</div>
)
}
}
结果.js
import React from 'react'
import Table from 'react-bootstrap/Table';
const Result = (props) => {
console.log('props value is:'+props.data)
let {searchCheck, searchValue}=props;
let update=props.data.reverse().map((item)=>{
const { countryInfo, country, cases, deaths, recovered, active, casesPerOneMillion} = item;
return(
(searchCheck)?country.includes(searchValue)?
<tbody>
<tr key={countryInfo._id}>
<td><img style={{height:'25px',width:'50px'}}src={countryInfo.flag}/></td>
<td>{country}</td>
<td>{cases}</td>
<td>{active}</td>
<td>{recovered}</td>
<th>{casesPerOneMillion}</th>
<td>{deaths}</td>
</tr>
</tbody>:
'':
<tbody>
<tr key={countryInfo._id}>
<td><img style={{height:'25px',width:'50px'}}src={countryInfo.flag}/></td>
<td>{country}</td>
<td>{cases}</td>
<td>{active}</td>
<td>{recovered}</td>
<th>{casesPerOneMillion}</th>
<td>{deaths}</td>
</tr>
</tbody>
)
})
return (
<div>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>Flag</th>
<th>Country</th>
<th>Cases</th>
<th>Active</th>
<th>Recovered</th>
<th>Cases per one Million</th>
<th>Deaths</th>
</tr>
</thead>
{update}
</Table>
</div>
)
}
export default Result;
【问题讨论】:
-
你好,能不能把你的项目上传到代码沙箱,这样就可以轻松修改代码了??
-
@FerinPatel 我在这里添加了它:codesandbox.io/s/confident-morning-u4fvm
标签: reactjs ecmascript-6