我的行有问题:
if (information && information.data && information.data.login == 1) navigation.navigate('DrawerNavigator')
我收到警告:
警告:无法在现有状态过渡期间进行更新(例如 在
render
中)。渲染方法应该是道具的纯粹功能 和状态。我的观点不是渲染
但是,如果information.data.login == 0
和调用是此行if (information && information.data && information.data.login == 0) navigation.navigate('StackNavigator')
一切都可以,我的视图渲染。
完整代码:
import React, { Component } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { connect } from "react-redux";
import { postDeviceid } from '../actions/deviceid';
import { ErrorScreen } from './ErrorScreen';
import { styles } from './AppScreen.style';
import PropTypes from 'prop-types';
class AppScreen extends Component {
componentDidMount() {
this.props.dispatch(postDeviceid());
};
render() {
const { information, error, loading, navigation } = this.props;
const isLoged = () => {
if (loading) {
return <ActivityIndicator size="large" color="#0000ff" />
}
if (error && error.status > 0) {
return <ErrorScreen error={error}></ErrorScreen>
} else {
if (information && information.data && information.data.login == 0) navigation.navigate('StackNavigator')
if (information && information.data && information.data.login == 1) navigation.navigate('DrawerNavigator')
}
};
return (
<View style={styles.container}>
{isLoged()}
</View>
);
}
};
const mapStateToProps = ({ deviceid }) => ({
information: deviceid.information,
error: deviceid.error,
loading: deviceid.loading
});
AppScreen.propTypes = {
loading: PropTypes.bool.isRequired,
error: PropTypes.array.isRequired,
information: PropTypes.object.isRequired
};
export default connect(mapStateToProps)(AppScreen);
这是因为您在渲染函数中调用状态过渡(navigation.navigate)。您需要在组件安装然后渲染时调用它。您可以使用道具有条件地渲染。因此,例如,如果传递了真实的加载状态,请对其进行测试并返回渲染方法中的加载组件。
将逻辑保留在渲染方法之外,因为它应该是纯的。
Render()函数应纯净,这意味着它不会修改组件状态,每次调用时都会返回相同的结果,并且不会直接与浏览器进行交互。
如果您需要与浏览器进行互动,请在 componentDidmount()或其他生命周期方法。保持 Render()Pure使组件更容易考虑。
https://reactjs.org/docs/reeact-component.html#render
import React, { Component } from "react";
import { View, ActivityIndicator } from "react-native";
import { connect } from "react-redux";
import { postDeviceid } from "../actions/deviceid";
import { ErrorScreen } from "./ErrorScreen";
import { styles } from "./AppScreen.style";
import PropTypes from "prop-types";
class AppScreen extends Component {
state = {};
componentDidMount() {
this.props.dispatch(postDeviceid());
this.isLoged();
}
isLoged = () => {
const { information, navigation } = this.props;
if (information && information.data && information.data.login == 0)
navigation.navigate("StackNavigator");
if (information && information.data && information.data.login == 1)
navigation.navigate("DrawerNavigator");
};
render() {
const { information, error, loading, navigation } = this.props;
if (loading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
if (error && error.status > 0) {
return <ErrorScreen error={error} />;
}
return <View style={styles.container}>
Youre page content
</View>;
}
}