【发布时间】:2021-02-07 17:57:36
【问题描述】:
当用户输入口袋妖怪并点击提交按钮时,我有一个涉及 PokeAPI 的反应项目,我希望它从 API 中获取口袋妖怪信息以及口袋妖怪从 API 中获得的类型信息。基本上我想进行一个需要来自另一个 api 调用的数据的 api 调用,我想在提交时执行此操作。
现在我让它在提交时获得口袋妖怪信息,并在提交后在不同的组件中获得类型信息,但我这样做的方式是无限期地重新渲染组件,我戴上了创可贴修复我非常想避免的问题。
function handleSubmit(dispatch) {
return (event) => {
event.preventDefault();
const pokemonNameID = new FormData(event.currentTarget).get('pokemon');
console.log(pokemonNameID);
api.getPokemon(pokemonNameID)
.then((response) => {
dispatch({
type: 'SELECTED_POKEMON',
payload: {
pokemon: response.body,
}
})
})
.catch((error) => {
console.log(error);
});
}
}
return (
<form action="" onSubmit={handleSubmit(props.dispatch)}>
<input className="search" type="text" placeholder="name/id" name="pokemon"/>
<input className="pkmn-button"type="submit"name="."value="."/>
</form>
)
}
Search.propTypes = {
dispatch: PropTypes.func,
}
export default connect(null)(Search);
class PokemonTypes extends Component {
shouldUpdate = true;
count = 0;
shouldComponentUpdate(){
if(this.shouldUpdate){
return true;
}
this.count=0;
this.shouldUpdate = true;
return false;
}
componentDidUpdate(){
var typeOne=this.props.pokemon.get("types").get(0).get("type").get("name");
var typeTwo=typeTwoExists(this.props.pokemon);
var dispatch = this.props.dispatch;
api.getType1(typeOne)
.then((response) => {
dispatch({
type: 'POKEMON_TYPE1',
payload: {
type1: response.body,
}
})
})
.catch((error) => {
console.log(error);
});
try{
api.getType2(typeTwo)
.then((response) => {
dispatch({
type: 'POKEMON_TYPE2',
payload: {
type2: response.body,
}
})
})
.catch((error) => {
console.log(error);
});
}catch(e){
}
this.count+=1;
if (this.count%2===0){
this.shouldUpdate = false;
}
}
render() {
var typeOne=this.props.type1.get("name");
//this.props.pokemon.get("types").get(0).get("type").get("name");
var typeTwo=typeTwoExists(this.props.pokemon);
return (
<div>
<IsPokemonTypes type1={typeOne}
type2={typeTwo} />
</div>
)
}
}
export default connect(mapStateToProps)(PokemonTypes);
当所有 api 调用都需要来自另一个也称为 onSubmit 的 API 调用的信息时,我该如何进行 onSubmit 调用?
【问题讨论】: