javascript - 使用 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
解决方案
我刚刚意识到这是两个部分的问题。
第一个问题是props.route.params
不受后续render()
调用的影响。这意味着即使您重新渲染组件,也会使用相同的初始属性。
第二个是getDerivedStateFromProps()
。每次调用渲染函数时,它都会getDerivedStateFromProps()
在它之前调用,将状态设置为初始路由参数。
这个问题可以通过以下方式解决:
- 初次使用后清除渲染函数中的初始路由参数。在函数开头有点像这样的东西
render()
会起作用。this.props.route.params = undefined
- 使用 if 语句和 state 中的变量来调节 props 何时应该更新 state。
- 重构代码以使用道具
选项 3 是应该如何正确完成事情,但最佳解决方案取决于您的代码如何工作。
推荐阅读
- c++ - 使用来自 boost::array 与 std::array 的 std::string::assign 不兼容
- javascript - 如何使用 Typescript 将每个时间间隔减少 10 分钟?
- eleventy - 如何通过前端变量(Eleventy / 11ty)过滤处理过的文件?
- python - 获取对比色的循环
- python - 根据 x、y、z 坐标用 python 绘制密度场
- jupyter - 如何在 Thonny IDE 上安装 XGboost?
- puppet - 如何使用单个 puppet erb 模板创建具有不同内容的两个不同文件
- javascript - 如何使用 setinterval 检查方法是否可用
- python - 如何使用 python 的 matplotlib 绘制日期时间段
- amazon-web-services - 每个 HTTP 请求生成一个新的预签名 URL 是否被认为是不好的做法?