You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中setState无法更新状态问题求助

React Native中setState执行后代码终止的问题解决

问题根源

你写的是函数组件,但犯了两个关键错误:

  1. 函数组件不存在this上下文,直接调用this.setState会抛出ReferenceError,这就是代码执行到此处终止的核心原因。
  2. 你定义的state只是普通常量对象,不是React的状态变量,即便不用this,直接修改它也无法触发组件重新渲染。

解决方案

改用函数组件的useState钩子管理屏幕状态,同时修正函数定义方式:

步骤1:替换普通state为useState

把原来的普通state对象替换为React状态变量:

// 替换原有const state = {...}
const [screenStates, setScreenStates] = React.useState({
  titleScreen: 'block',
  createAccountScreen: 'none',
  hubScreen: 'none',
  deliveryScreen: 'none',
  notesScreen: 'none',
  tutoringScreen: 'none',
  profileScreen: 'none',
  usernameLogin: '',
  passwordLogin: '',
  initialState: 0,
});

步骤2:修改loggedIn函数

删除this.setState,改用setScreenStates,同时修正函数声明方式(函数组件内用const定义函数):

const loggedIn = () => {
  console.log('Test 1');
  // 展开原有状态,仅修改需要更新的字段,保证状态不可变性
  setScreenStates({
    ...screenStates,
    titleScreen: 'none',
    createAccountScreen: 'block',
  });
  console.log('Test 2');
};

步骤3:清理无用导入

因为用的是函数组件,无需导入Component,删除这行代码:

// 移除无用导入
import { Component } from 'react';

完整修正后的代码片段

import React, { useState } from 'react';
import { AppRegistry, Text, View, TouchableHighlight } 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] = 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'},
  ]

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

  // 用useState管理状态
  const [screenStates, setScreenStates] = useState({
        titleScreen: 'block',
        createAccountScreen: 'none',
        hubScreen: 'none',
        deliveryScreen: 'none',
        notesScreen: 'none',
        tutoringScreen: 'none',
        profileScreen: 'none',
        usernameLogin: '',
        passwordLogin: '',
        initialState: 0,
    });

  // 修正后的函数定义
  const loggedIn = () => {
        console.log('Test 1');
        setScreenStates({
          ...screenStates,
          titleScreen: 'none',
          createAccountScreen: 'block',
        });
        console.log('Test 2');
    };

  // 补充组件返回的JSX(原代码缺失部分)
  return (
    <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
      <TouchableHighlight onPress={loggedIn} style={{padding:10, backgroundColor:'#ccc'}}>
        <Text>触发登录逻辑</Text>
      </TouchableHighlight>
    </View>
  );
};

AppRegistry.registerComponent('App', () => App);

关键说明

  • 函数组件必须用useState/useReducer等钩子管理状态,不能使用类组件的this.setState。
  • 更新状态时要遵循不可变性原则,用展开运算符...保留原有状态字段,避免意外覆盖其他状态。
  • 函数组件内的自定义函数需用const声明,不能使用类组件的函数名 = () => {}写法。

内容的提问来源于stack exchange,提问作者Liam Morley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:55:26