componentDidUpdate在第一次安装组件后没有触发(React)。

问题描述 投票:0回答:1

我有一个功能,通过点击一个按钮来切换单页上的窗口(组件)。

交换窗口的函数。

getProfileContent = () => {
    var html = [];
    if (this.state.content === "picks") {
        html.push(<Picks picks={this.state.picks} deletePick={this.deletePick} />);
    }

    if (this.state.content === "api") {
        html.push(<Admin admin="admin" />);
    }

    if (this.state.content === 'settings') {
        html.push(<Settings />);
    }

    return html;
};

当父组件初始加载时,内容默认为 "pick",而当 "Pick "组件第一次加载时,一切都很正常,因为触发了下面的componentDidUpdate更新函数。

"Picks "组件更新函数。

componentDidUpdate(prevProps, prevState) {
    console.log('here')
    if (Object.keys(prevProps.picks).length !== Object.keys(this.props.picks).length) {
        this.sortPicks();
    }
}

但是,通过交换窗口后 getProfileContent 回过头来 "选择" 组成部分 componentDidUpdate 函数没有被触发。 我也试过给Pick组件添加不同的 "key "值,希望新的道具能触发这个功能。componentDidUpdate但是没有成功。 我把控制台日志放在条件外,所以我知道 componentDidUpdate 没有被调用,不管条件如何。任何帮助都是值得赞赏的,谢谢!我有一个函数,通过点击一个按钮来切换单个页面上的窗口(组件)。

javascript reactjs web components react-props
1个回答
1
投票

有可能是props值没有改变,因此相同的props值被传递下来,因此具有相同的长度。很有可能是达到了 componentDidUpdate() 钩子,但是条件返回false,因此你没有进入到 sortPicks() 函数。在不知道其他代码的情况下,很难说。


0
投票

这个问题在@lanxion的帮助下已经解决了。 基本上,组件第一次挂载时,会调用 componentDidUpdate 函数,但只是因为父组件更新并传递了新的道具。 第二次挂载组件时,父组件已经有了正确的道具,因此只调用了 componentDidMount,而没有调用 componentDidUpdate。 将代码放在 componentDidMount 和 componentDidUpdate 中(带条件),解决了我的问题。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.