我希望使用戳戳Api来搜索在搜索表中输入的任何神奇宝贝。
当我输入神奇宝贝时,它不会向显示组件返回任何内容。使用开发工具(“网络”选项卡),可以看到返回了响应对象。我似乎无法弄清楚为什么它不呈现。在通过添加端点的硬编码值并使其呈现良好之前,我已经在添加搜索功能之前测试了该呼叫。
应用程序组件
class App extends Component {
state = {
pokemonData: {},
pics: {}
}
searchPokemon(pokemon) {
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`)
.then(response => response.json())
.then(data => this.setState({pokemonData: data, pics: data.sprites}))
.catch(error => `Error fetching and parsing data ${error}`)
}
render() {
return (
<>
<Header/>
<Container className="main-container">
<Container className="search-container">
<Pokeform onSearch={this.searchPokemon}/>
</Container>
<Container className="display-container">
<Display data={this.state.pokemonData} type={this.state.types} pics={this.state.pics}/>
</Container>
</Container>
</>
);
}
}
Form和Display组件当然都是单独的文件。
state = {
searchText: ''
}
onSearchChange = e => {
this.setState({searchText: e.target.value})
}
handleSubmit = e => {
e.preventDefault();
this.props.onSearch(this.state.searchText);
e.currentTarget.reset();
}
render() {console.log(this.props.onSearch(this.state.searchText));
return (
<>
<Form className="poke-form" onSubmit={this.handleSubmit}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Enter Pokemon Name</Form.Label>
<Form.Control
className="search-input"
type="search"
onChange={this.onSearchChange}
placeholder="Who are you searching for..."
name="search"
/>
</Form.Group>
<Button className="search-btn" variant="primary" type="submit">
Search
</Button>
</Form>
</>
);
}
}
const Display = (props) => {
return (
<>
<h1 className="pokemon-name">{props.data.name}</h1>
<p>Pokemon number #{props.data.id}</p>
<img src={props.pics.front_default} className="img-fluid" alt="pokemon-pic-front"/>
<img src={props.pics.back_default} className="img-fluid" alt="pokemon-pic-back"/>
</>
);
}