【问题标题】:Check parent mounting status when updating state from a child component从子组件更新状态时检查父挂载状态
【发布时间】:2025-12-24 17:00:06
【问题描述】:

在我的 react native 0.59.9 应用程序中,App 类有 2 个状态,可以由子组件更新。

class App extends React.Component {

  state = {
    group_id: this.props.navigation.state.params.data.group_id,
    result: this.props.navigation.state.params.data.result,  
  };

 updateGroup = (group_id) => {
    console.log("In updateGroup : ", group_id);
    this.setState({group_id:group_id});
  };

  updateToken = (token) => {
    console.log("In updateToken : ", token);
    this.setState({result: token});
  };

const EventWithSelf = (props) => (<Event {...props} updateToken={this.updateToken}  />)
const GroupWithSelf = (props) => (<Group {...props} updateGroup={this.updateGroup} updateToken={this.updateToken} />);   
..........
}

EventGroup 是可以更新App 状态的子组件。 在updateGroupupdateToken 中,应用程序如何在执行setState 之前检查App 的挂载状态?我担心的是App 在执行setState 时可能无法安装。这肯定会抛出警告。

更新:

updateToken 位于 componentDidMount 中,位于 EventGroup 中。 updateGroup 通过点击触发。代码如下:

async _onPress(id) {
      let element = this.state.activeGroups;
      let element1 = element.find((e) => {
        console.log("e is ", e);
        return (e.id == id);
      });
      //save group_id clicked
      try {
        console.log("saved group id in Group : ", element1.id);
        await helper.setMyValue("group_id", element1.id.toString());
      } catch (err) {
        console.log("error in saving group_id to local disk", err);
      };
      this.props.updateGroup(element1.id); //<<<=== this causes "warning of no-op with updating unmounted component" in `Event` component.
      this.props.navigation.navigate("Event", {group_id:element1.id});
      return;
    }

【问题讨论】:

  • 这取决于您何时调用 updateGroup 和 updateToken 方法。可以分享一下事件和组组件代码吗?
  • Amardeep Singh,已更新。 updateToken 位于 EventGroup 的 componentDidMount 中。 updateGroup 通过点击触发。

标签: reactjs react-native react-component react-state


【解决方案1】:

使用componentDidMount生命周期方法设置flag,然后将此标志传递给子组件。

定义标志isMounted:

constructor(props) {
        super(props);
        this.state = {
            isMounted: false,
        };
    }

在组件挂载时将isMounted 设置为true

componentDidMount(){
    this.setState=({ isMounted: true })
}

然后传给孩子们。

<Event {...props} isMounted={this.state.isMounted} updateToken={this.updateToken}  />

然后,您可以在子组件中执行setState之前,使用isMounted标志检查App的挂载状态。

【讨论】:

  • 有没有办法保证updateTokenupdateGroup的执行?在App.js 中更新resultgroup_id 非常重要。
  • @user938363 只要你的组件被挂载,你就可以更新它的状态。您可以使用componentWillUnmount 生命周期方法将isMounted 标志设置为falsecomponentWillUnmount 在组件卸载之前被调用。
  • 添加 _isMounted 作为类变量并在setState之前检查它。