【发布时间】:2018-08-07 03:10:15
【问题描述】:
我试图在下面的屏幕中有条件地显示 Home 或 Slider 组件,但是当 onDone 函数运行时,我收到错误:
警告:只能更新已安装或已安装的组件。这通常意味着您在未安装的组件上调用了 setState、replaceState 或 forceUpdate。这是一个无操作。 请检查 Onboarding 组件的代码。
Onboarding 组件位于 Slider 内部(react-native-onboarding-swiper - 用于应用介绍)...
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;
【问题讨论】:
-
您可以尝试将
componentDidMount替换为componentWillMount吗?我今天早上才这样做,因为我有同样的错误,它修复了错误 -
试过了,同样的错误...
-
试试这个 this.setState((state) => { introLoaded: true }); .与 componentDidMount
-
Erf ...您可以尝试将您的状态放入构造函数中吗?像这样 `constructor(props){ super(props); this.state = { introLoaded: false, } }``
-
请解释一下您想从 Slider 组件中实现什么?因为它是一个无状态组件,为什么还要使用 async await 来更新 HomeScreen 的状态?
标签: javascript react-native setstate asyncstorage