React Native / Redux - 只能更新已安装或安装的组件

React Native / Redux - Can only update a mounted or mounting component

我只是从服务器获取项目并将它们显示在列表组件中。组件结构就像

ServiceScreen(parent) -> ServicesList(child- used inside ServiceScreen) -> ServiceItem (child used inside ServicesList)

一切正常,它显示获取的服务,但它给了我以下警告

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op. Please check the code for the YellowBox component.

代码如下

ServiceScreen.js

constructor(props) {
    super(props);
    this.props.actions.fetchServices();
  }
    render() {
        const { isFetching } = this.props;
        return (
          <View style={styles.container}>
            <ServicesList services={this.props.services} navigation={this.props.navigation} />
          </View>
        );
      }

ServicesList.js

render() {
    return (
      <View style={{ flex: 1 }}>
        <FlatList
            data={this.props.services}            
            renderItem={
                ({ item }) => 
                <ServiceItem navigation={this.props.navigation} item={item} />
            }
        />
      </View>
    );
  }

ServiceItem.js

render() {
        const { item } = this.props;
        return (
            <TouchableOpacity onPress={this.singleService}>
                <Text>{item.service_name}</Text>
            </TouchableOpacity>
        );
    }

因为我使用redux做状态管理,所以我已经映射了服务 状态到我的 ServiceScreen 组件。我将它传递给 child 组件。

您应该在 componentDidMount 中调度操作。在安装组件之前调用构造函数,这就是您看到错误的原因。

这是反应生命周期的图表。您应该只调用在 "commit" 阶段更改状态的方法。

这个错误正是在黄色框中所说的时候触发的。您在某处尝试更新已卸载的组件。 我通过使用临时变量 componentIsMounted: bool 和包装 setState 方法来处理这个问题:

class SomeClass extends Component {
  constructor(props) {
    this._isComponentMounted = false;
  }

  componentDidMount() {
    this._isComponentMounted = true;
  }

  componentWillUnmount() {
    this._isComponentMounted = false;
  }

  setState(...args) {
    if (!this._isComponentMounted) {
      return;
    }

    super.setState(...args);
  }
}

另外,你应该记住,你不应该在组件挂载之前调用状态更新(这不是替代方法 - 只是一个补充)。