通过组件间传值方法更新接口重新render新数据
前提描述:
现有一功能,在子组件A里左右切换选择不同的时间,将选择的时间值传给兄弟组件B,子组件B重新请求接口,获取新数据并重新渲染。
文件分级:
父组件:CarReport.jsx
子组件A:TimeChoose.jsx
子组件B:Day’Operate.jsx
ui图示:
实现方式:
1.先将子组件A里的时间值传给父组件,父组件在传给子组件B,也就是兄弟组件间的传值(组件间的传值可借鉴上一篇)
2.子组件A切换时间,子组件B获取到新的时间,重新请求接口,这时需要用到一个生命周期函数:componentWillReceiveProps(nextProps){ }
class DayOperate extends React.Component{
constructor(props){
super(props);
this.state = {
func:this.getReport(this.props.choseTime) //这是页面初始化时调用函数请求接口
}
}
// 这是子组件A把时间传给当前子组件B时,再次请求接口,需要使用
componentWillReceiveProps(nextProps){
if(this.props.choseTime != nextProps.choseTime){
this.getReport(nextProps.choseTime); //调用函数,重新请求接口
}