【发布时间】:2019-04-01 08:01:29
【问题描述】:
getDerivedStateFromProps 不允许我调用 this 函数来调用 API。该组件接受项目 id 并使用该 id 我需要在渲染之前调用 api。
我尝试在 componentDidUpdate 中调用 api,但在渲染后不起作用。 componentWillReceiveProps 在实际 props 接收之前调用 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}&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
}
}
【问题讨论】:
-
在使用旧的 api id 反应更新 dom 之后调用 compoenentDidUpdate api。所以一切都被一个 id 延迟了
标签: reactjs