前言
日常积累,欢迎指正
正文
需求
有这样一个需求: props.planId
修改就要触发 getPlanDetailByPlanId(planId : string|number)
当然会相应有一个 state.data ,在 get 方法中根据 id 请求到正确的数据后再 setState({data})
就能实现页面正确结果的显示啦!
处理思路
在 react 未更新的版本中这种情况在生命周期方法 componentWillReceiveProps
中处理,但在新生命周期中我们不再使用这个方法,初学 react 新生命周期时我们一般都会了解到有一个用于替代 componentWillReceiveProps 的生命周期方法 static getDerivedStateFromProps()
所以马上想到在这个方法里面触发编写的 getPlanDetailByPlanId 方法。
但是请注意生命周期方法 getDerivedStateFromProps 的修饰符 static
,之前的思路就行不通了,那到底该怎么处理呢?我目前的解决办法是在 shouldComponentUpdate
方法中处理:
shouldComponentUpdate(nextProps, nextState) { const { planId } = nextProps if (this.props.planId !== planId) { this.getPlanDetailByPlanId(planId) } return true } getPlanDetailByPlanId = (planId: string | number) => { axios.get(`http://localhost:3000/plans/${planId}`).then((res : any)=> { this.setState({ data : res.data }) }) }
总结
shouldComponentUpdate
方法中做这样的处理总是感觉有点哪里怪怪的,赶项目中暂不纠结。
文章来源: https://blog.csdn.net/m0_37148591/article/details/90371665