【问题标题】:'TypeError: Cannot read property 'state' of undefined' error' in react-native'TypeError:无法读取反应原生中未定义'错误'的属性'状态'
【发布时间】:2020-03-26 13:35:53
【问题描述】:

我已经使用 defaultNavigationOptions 创建了标题导航栏包含主页、注册、登录、创建博客选项。如果用户已登录,则登录选项不应可见,而是应启用注销选项。我正在使用 AsyncStorage 来存储令牌。

App.js:

import React from 'react';
import { CreateBlog } from './app/views/CreateBlog.js';
import { BlogDetails } from './app/views/BlogDetails.js';
import { EditBlog } from './app/views/EditBlog.js';
import { DeleteBlog } from './app/views/DeleteBlog.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { Home } from './app/views/Home.js';
import { Login } from './app/views/Login.js';
import {
  StyleSheet, Text, View, TextInput, TouchableHighlight, Alert, AsyncStorage
} from 'react-native';
import { Signup } from './app/views/Signup.js';

const AppNavigator = createStackNavigator(
  {
    CreateBlogRT: {
      screen: CreateBlog
    },
    BlogDetailsRT: {
      screen: BlogDetails
    },
    EditBlogRT: {
      screen: EditBlog
    },
    DeleteBlogRT: {
      screen: DeleteBlog
    },
    SignupRT: {
      screen: Signup
    },
    LoginRT: {
      screen: Login
    },
    HomeRT: {
      screen: Home,
    },
  },
  {
    initialRouteName: 'HomeRT',
      defaultNavigationOptions: ({ navigation }) => ({

      header: <View style={{
        flexDirection: "row",
        height: 80,
        backgroundColor: '#f4511e', fontWeight: 'bold'
      }} >
        <TouchableHighlight onPress={() => navigation.navigate('SignupRT')}>
          <Text > SignUp</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={() => navigation.navigate('CreateChapterRT')}>
          <Text > CreateChapter</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={() => navigation.navigate('LoginRT')}>
          <Text > Login</Text>
        </TouchableHighlight>
//getting 'TypeError: Cannot read property 'state' of undefined'
        {this.state.logged_in &&

          <TouchableHighlight onPress={async () => {
            await AsyncStorage.removeItem('token');
            await AsyncStorage.removeItem('user_id');
          }}>
            <Text > Logout</Text>
          </TouchableHighlight>
        }
      </View >
    }),
  },


  }
);
const MyRoutes = createAppContainer(AppNavigator);
export default class App extends React.Component {
     constructor(props) {
      super(props);
     this.state = { logged_in: false };
    }
     componentDidMount = async () => {
       var logged_in = await AsyncStorage.getItem('token')
      this.setState({ logged_in: false })

     }

  render() {
    return (
      <MyRoutes />

    );
  }
}

现在单击注销按钮时,它会删除令牌。我希望只有在用户登录时才能看到注销按钮。同样的登录和注册选项也是如此。 (

const loggedin=AsyncStorage.getItem('token');if(userloggedin) 
{showlogout:true;showlogin:false;showSignup:false}.

我不知道在哪里写代码。提前致谢。

【问题讨论】:

    标签: react-native navigation asyncstorage stack-navigator


    【解决方案1】:

    登录用户后可以设置userloggedin为真

    AsyncStorage.setItem('userloggedin',JSON.stringfy(true)
    

    AsyncStorage.setItem('userloggedin',Boolean(true))
    

    然后获取项目

    const logged-in = AsyncStorage.getItem('userloggedin')
    
    if(loggedin){
    showlogout=true
    showlogin=false
    showSignup=false
    
    or if your are using state
    
    this.setState({
    showlogout:true,
        showlogin:false,
        showSignup:false})
        }.
    

    【讨论】:

    • render(){ const logged_in=AsyncStorage.getItem('token');} 但它给出了 logged_in 值作为 Promise。我们必须使用 Async 和 await 关键字和 AsyncStorage 来写入承诺值。如果我只是写 const logged_in = await AsyncStorage.getItem('token') 那么它会抛出错误。我在哪里/如何使用异步关键字??
    【解决方案2】:

    你可以使用 react 生命周期来完成这项工作,也可以使用全局变量或状态,像这样

    检查这张图片

    https://camo.githubusercontent.com/3beddc08b0e4b44fbdcef20809484f9044e091a2/68747470733a2f2f63646e2d696d616765732d312e6d656469756d2e636f6d2f6d61782f323430302f312a736e2d66746f7770305f565652626555414645434d412e706e67

        class Clock extends React.Component {
          constructor(props) {
            super(props);
            this.state = {logged_in: false};
          }
    
          componentDidMount=async() {
        var logged_in = await AsyncStorage.getItem('token')
       this.setState({logged_in: false})
          }
    
    
          render() {
        const {logged_in} = this.state
            return (
              <div>
                <h1>Hello, world!</h1>
                <h2>It is {logged_in}.</h2>
              </div>
            );
          }
        }
    

    【讨论】:

    • 感谢您的回复。现在我得到'TypeError:无法读取未定义'错误'的属性'状态'。我已经编辑了我的帖子..
    • 您好,您收到此错误,TypeError:无法读取未定义“错误”的属性“状态”。你的问题类组件状态未定义的意思,你的问题“this”请检查并调试 render(){ console.log(this,'my component ref this')
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2020-05-16
    • 2019-07-25
    相关资源
    最近更新 更多