首页 > 解决方案 > 使用 onChangeText React Native 时 this.setState 不改变状态

问题描述

我尝试了一些方法来获取 setState() 来更新状态的值。目前,文本中的内容发生了<TextInput>变化,但中的值this.state没有改变。

console.log在正确的地方,我尝试过编写外部函数,我弄乱了变量的名称,但似乎没有任何效果。

import * as React from 'react';
import { View, Text, TextInput, TouchableHighlight, Dimensions, StyleSheet } from "react-native";

import PropTypes from "prop-types";

class EditNote extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      title: '',
      text: '',
      id: ''
    }
  }

  // TODO: Change textboxes to match the props from the NoteList
  static getDerivedStateFromProps(props){
    return(
      {...props.route.params}
    )
  }

  render(){
    return(
      <View style={s.container}>
        <View style={s.titleContainer}>
          <Text style={s.titleText}>Edit Note</Text>
          <View style={{flex: 1}}/>
        </View>
        <View style={s.inputContainer}>
          <TextInput
            style={{...s.input, ...s.titleInput}}
            autoCapitalize='words'
            keyboardAppearance='dark'
            placeholderTextColor='#DDD'
            onChangeText={(title) => { this.setState({title: title}, () => console.log(this.state)) }}
            defaultValue={this.state.title}
          />
          <TextInput
            style={{...s.input, ...s.textInput}}
            autoCapitalize='sentences'
            keyboardAppearance='dark'
            placeholderTextColor='#DDD'
            multiline
            onChangeText={(text) => { this.setState({text: text}, () => console.log(this.state)) }}
            defaultValue={this.state.text}
          />
        </View>
        
        <View style={s.buttonContainer}>
          <TouchableHighlight
            style={s.backButton}
            onPress={() => this.props.nav.navigate('NoteListView')}
            underlayColor='#300030'
          >
            <Text style={s.buttonText}>Cancel</Text>
          </TouchableHighlight>
          <TouchableHighlight
            style={s.addButton}
            onPress={() => {
              console.log(this.state.note)
              this.props.nav.navigate('NoteListView', {note: this.state, mode: 'edit'})
            }}
            underlayColor='#300030'
          >
            <Text style={s.buttonText}>Edit</Text>
          </TouchableHighlight>
        </View>
      </View>
    )
  }
}

export default EditNote

标签: javascriptreact-nativesetstate

解决方案


我刚刚意识到这是两个部分的问题。

第一个问题是props.route.params不受后续render()调用的影响。这意味着即使您重新渲染组件,也会使用相同的初始属性。

第二个是getDerivedStateFromProps()。每次调用渲染函数时,它都会getDerivedStateFromProps()在它之前调用,将状态设置为初始路由参数。

这个问题可以通过以下方式解决:

  1. 初次使用后清除渲染函数中的初始路由参数。在函数开头有点像这样的东西render()会起作用。this.props.route.params = undefined
  2. 使用 if 语句和 state 中的变量来调节 props 何时应该更新 state。
  3. 重构代码以使用道具

选项 3 是应该如何正确完成事情,但最佳解决方案取决于您的代码如何工作。


推荐阅读