简体   繁体   English

this.setState 在使用 onChangeText React Native 时不会改变 state

[英]this.setState not changing state when using onChangeText React Native

I've tried a few methods to get setState() to update the value of state.我尝试了一些方法来获取 setState() 来更新 state 的值。 Currently the text in the <TextInput> changes, but the value in this.state doesn't change.目前<TextInput>中的文本发生了变化,但this.state中的值没有变化。

I have the console.log in the right place, I've tried writing external functions, I've messed around with the variable's names but nothing seems to work.我将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

I just realized that this is a problem with two parts.我刚刚意识到这是两个部分的问题。

The first problem is that props.route.params is unaffected by subsequent render() calls.第一个问题是props.route.params不受后续render()调用的影响。 This means that even if you re-render the component, the same initial properties are used.这意味着即使您重新渲染组件,也会使用相同的初始属性。

The second is getDerivedStateFromProps() .第二个是getDerivedStateFromProps() Every time the render function is called it calls getDerivedStateFromProps() right before it which sets the state to the initial route parameters.每次调用渲染 function 时,它都会在它之前调用getDerivedStateFromProps() ,将 state 设置为初始路由参数。

This problem can be fixed by:这个问题可以通过以下方式解决:

  1. Clearing the initial route parameters in the render function after their initial use.在初次使用后清除渲染 function 中的初始路由参数。 Something a little like this at the beginning of the render() function will work.render() function 的开头有点像这样的东西会起作用。 this.props.route.params = undefined
  2. Using an if statement and a variable in state to regulate when the props should update the state.在 state 中使用 if 语句和变量来调节道具何时应该更新 state。
  3. Refactor the code to make use of the props重构代码以使用道具

Option 3 is how things should be correctly done but the best solution depends on how your code works.选项 3 是应该如何正确完成事情,但最佳解决方案取决于您的代码如何工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM