【问题标题】:I have an api call that I need to invoke before the second render after it receive new props我有一个 api 调用,我需要在接收新道具后的第二次渲染之前调用它
【发布时间】: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


【解决方案1】:

尝试在componentDidUpdate中添加一个if条件来检查isActive是否改变了

componentDidUpdate(prevProps){
    if(prevProps.isActive !== this.props.isActive){
        this.getRecipe(this.props.isActive);
    }        
}

这只会在 isActive 的 props 值改变时调用 getRecipe 函数

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 2019-01-27
    • 2013-02-17
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多