【问题标题】:How to delay parent component from rendering until a setState in child component has finished?如何延迟父组件的渲染,直到子组件中的 setState 完成?
【发布时间】:2019-12-17 11:06:51
【问题描述】:

**parent-component**

    class MatchVideos extends Component {
        DaySelector = createRef();  //creating ref for child-component

        componentDidMount() {

            utils.getData().then((response) => {

            this.setState({ dayData: response.data }, () => {
                 this.getData(this.DaySelector.current.state.currentDay);  //calling a method in parent by passing child-component data
            });

            })
            .catch(err => {
               if (err.response) {
               this.setState({ isError: true })
               }
            })
       }

    render(){
       return(
       <DaySelector ref={this.DaySelector}/>
       )
    }
    }

**child-component(DaySelector)**

componentDidMount(){
        let data = {
            "trn_year": utils.trn_year,
            "trn_id": utils.trn_id
        }
        utils.getDay(data).then((response) =>{
            this.dates = response.data.dayWise;
            var curDay = this.dates.filter(function(day) {
                console.log(new Date().toISOString().split('T')[0]);
                return( day.Date === "2019-01-19"
            )
            })
            this.setState({currentDay: curDay[0].Day, selectedDay: curDay[0].Day}, ()=>{  //this is the state I want to access in parent-component.
                utils.selected_day = this.state.selectedDay;
                utils.selected_date = curDay[0].Date;
            });                          
        })
    }

所以我们知道父组件的componentDidMount只有在所有子组件的componentDidMount方法都执行完之后才会执行。但是我的问题是父方法中 Dayselector 的 ref 为空(当前:null)的五分之一。如您所见,我在父组件中使用子组件(日选择器)的状态。我认为问题是子方法中的 setState 需要一些时间,而父方法同时使用空值执行。如何解决这个问题?如果我的问题有误或完全偏离主题,请纠正我。我所需要的只是父组件应该在子组件中有数据之后呈现。

我只展示了理解我的问题所需的代码

【问题讨论】:

  • 以另一种方式思考,例如在父组件中保存一个加载状态变量并将其设为 true,因此该值不会为 null,一旦该值存在,它将显示正在加载,您可以将其设为 false 并传递该值通过使用回调函数向父级显示值,这对你有用吗?
  • @DILEEPTHOMAS 我没有安静地跟随。我们正在根据子项中选择的日期加载父项中的数据。
  • @dharani 你能创建一个可重现问题最少的代码框,以便找到它会有所帮助
  • 您是否尝试过将状态逻辑移动到父级本身并将相关的道具/功能传递给子级,这是 React Docs 推荐的方法之一 - reactjs.org/docs/lifting-state-up.html
  • @n4m31ess_c0d3r 我猜提升状态会起作用。你能告诉我如何在我的代码上下文中做到这一点吗?

标签: javascript reactjs


【解决方案1】:

Hey React 有这些很酷的东西叫做 React lazyReact Suspense

您可以查看来自Siddharth Kshetrapal的这个很酷的视频视频

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多