#reactjs
#reactjs
Вопрос:
getDerivedStateFromProps не позволяет мне вызывать this
функцию для вызова API. Компонент принимает идентификатор элемента, и с этим идентификатором мне нужно вызвать api перед рендерингом.
Я пытался вызвать api в componentDidUpdate, не работает с момента его после рендеринга. componentWillReceiveProps вызывает вызов api до получения фактического реквизита.
class Recipe extends PureComponent{
constructor(props){
super(props)
this.state = {isLoading:true}
}
componentDidUpdate(){
console.log(this.props.isActive)
this.getRecipe(this.props.isActive);
}
getRecipe = async(id='47032')=>{
try {
const key = 'apikey';
const res = await axios.get(`https://www.food2fork.com/api/get?key=${key}amp;rId=${id}`);
console.log(res.data)
const get_ingredients = res.data.recipe.ingredients;
const newGet_ingredients = this.parseIngredients(get_ingredients);
res.data.recipe.ingredients = newGet_ingredients;
this.Recipe = res.data
this.setState({
isLoading:false
})
}
catch (err) {
console.log(err);
alert('Something went wrong :(')
}
}
render(){
console.log(this.Recipe)
if(!this.state.isLoading)
return(
<div className="recipe">
api data
</div>)
else return null
}
}
Комментарии:
1. С compoenentDidUpdate api вызывается после react update dom со старым идентификатором api. итак, все было отложено на один идентификатор
Ответ №1:
Попробуйте добавить условие if внутри componentDidUpdate, чтобы проверить, изменился isActive или нет
componentDidUpdate(prevProps){
if(prevProps.isActive !== this.props.isActive){
this.getRecipe(this.props.isActive);
}
}
это вызовет функцию getRecipe только после изменения значения реквизита isActive