React Native:setState + unmounted或mount component

时间:2018-02-27 12:54:04

标签: javascript react-native setstate asyncstorage

我试图在下面的屏幕中有条件地显示Home或Slider组件,但是当onDone函数运行时,我收到错误:

警告:只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState,replaceState或forceUpdate。这是一个无操作。 请检查热门组件的代码。

Onboarding组件位于Slider内(react-native-onboarding-swiper - 用于app简介)......

export default class HomeScreen extends Component {
  static navigationOptions = {
    headerStyle: {
      backgroundColor: 'skyblue',
      elevation: 0,
      borderBottomWidth: 0,
    },
    headerLeft: null,
  };

  state = {
    introLoaded: false,
  };

  async componentDidMount() {
    const value = await AsyncStorage.getItem('@SKIP_INTRO');
    if (value !== null) {
      this.onDone();
    }
  };

  onDone = async () => {
    await this.setState({ introLoaded: true });
  };

  render() {
    return this.state.introLoaded ? (
      <Home navigation={this.props.navigation} />
    ) : (
      <Slider onDone={this.onDone} />
    );
  }
}

任何帮助表示赞赏...

Slider.js

import React from 'react';
import { Image, Text } from 'react-native';
import PropTypes from 'prop-types';
import Onboarding from 'react-native-onboarding-swiper';
import styles from './styles';

const Slider = ({ onDone }) => (
  <Onboarding
    pages={[
      {
        backgroundColor: 'skyblue',
        image: (
          <Image source={require('../../assets/images/intro/pic1.png')} style={styles.image} />
        ),
        title: <Text style={styles.title}>Title 1</Text>,
        subtitle: <Text style={styles.subtitle}>Subtitle 1</Text>,
      },
      {
        backgroundColor: 'skyblue',
        image: (
          <Image source={require('../../assets/images/intro/pic2.png')} style={styles.image} />
        ),
        title: <Text style={styles.title}>Title 2</Text>,
        subtitle: <Text style={styles.subtitle}>Subtitle 2</Text>,
      },
    ]}
    onDone={onDone}
  />
);

Slider.propTypes = {
  onDone: PropTypes.func.isRequired,
};

export default Slider;

1 个答案:

答案 0 :(得分:0)

首先 setState 不是异步方法。有关详细信息read here

您的方法中的第二个HomeScreenonDone生命周期方法中调用方法componentDidMount,因为安装的组件将自动卸载Slider并在您更改状态时显示错误

因此,在无状态组件中使用Onboarding而不是在状态组件中使用它,并在欢迎屏幕(用户未登录并首次查看)的屏幕中使用它。用户登录后只需导航到另一个屏幕,这样用户将无法再看到此欢迎屏幕。 如果您需要更多信息,请与我们联系。

相关问题