React Native setState不更新状态- javascript

k2arahey  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(169)

我试图使用setState方法来更新状态,但是每当我执行函数时,一旦到达setState方法,一切都停止了。但是,所有代码直到函数工作。

import React, { Component } from 'react';
import { useState } from 'react';
import { AppRegistry, Text, View, StyleSheet, Image, TextInput, ImageBackground, TouchableHighlight, Alert, Dimensions, ScrollView, ActivityIndicator} from 'react-native';
import { SelectList } from 'react-native-dropdown-select-list';
import { MultipleSelectList } from 'react-native-dropdown-select-list';

import Constants from 'expo-constants';

const App = () => {

  const [selected, setSelected] = React.useState("");
  
  
  const data = [
      {key:'1', value:'Mobiles', disabled:true},
      {key:'2', value:'Appliances'},
      {key:'3', value:'Cameras'},
      {key:'4', value:'Computers', disabled:true},
      {key:'5', value:'Vegetables'},
      {key:'6', value:'Diary Products'},
      {key:'7', value:'Drinks'},
  ]

  let deviceHeight = Dimensions.get('window').height;
  let deviceWidth = Dimensions.get('window').width;

  const state = {
        titleScreen: 'block',
        createAccountScreen: 'none',
        hubScreen: 'none',
        deliveryScreen: 'none',
        notesScreen: 'none',
        tutoringScreen: 'none',
        profileScreen: 'none',
        usernameLogin: '',
        passwordLogin: '',
        initialState: 0,
    }
loggedIn = () => {
        console.log('Test 1')
        this.setState({
          titleScreen: 'none',
          createAccountScreen: 'block',
          hubScreen: 'none',
          deliveryScreen: 'none',
          notesScreen: 'none',
          tutoringScreen: 'none',
          profileScreen: 'none',
        })
        console.log('Test 2');
        
    }

我在网上研究了可能的解决方案,并试图使用箭头函数,但这并没有解决我的问题。我还将短语记录到控制台,以查看调用函数时是否发生了任何事情,并发现函数一传递方法就停止了。

mgdq6dx1

mgdq6dx11#

你似乎混淆了React Native中的类和函数。在示例中,您使用的是React.useState(参见here)和setState(参见here)。两者做同样的事情,但以不同的方式。
你可以这样修改代码:

const [selected, setSelected] = React.useState({
  titleScreen: 'block',
  createAccountScreen: 'none',
  hubScreen: 'none',
  deliveryScreen: 'none',
  notesScreen: 'none',
  tutoringScreen: 'none',
  profileScreen: 'none',
  usernameLogin: '',
  passwordLogin: '',
  initialState: 0
 });

然后,你的loggedIn函数:

loggedIn = () => {
  console.log('Test 1')
  setSelected({
    titleScreen: 'none',
    createAccountScreen: 'block',
    hubScreen: 'none',
    deliveryScreen: 'none',
    notesScreen: 'none',
    tutoringScreen: 'none',
    profileScreen: 'none',
  })
  console.log('Test 2');
}

在这种情况下,state变量是无用的。使用setSelected函数后,可以使用selected访问变量。
我不能100%确定这是否回答了你的问题,但我希望它至少能给予你关于如何在React中使用状态的信息:)

相关问题