У меня проблемы с отображением моего state. Начальное значение моего состояния empty, но когда я нажимаю кнопку state change.
Я хочу увидеть это изменение немедленно, но state только renders когда начну что-то печатать в моем Textinput
Это мое состояние:
constructor(props) {
super(props)
this.state = {
noteText: '',
userName:'',
}
}
Я меняю состояние с помощью кнопки onPress
changeState(){
this.setState({userName:'Kevin'})
}
Здесь я отдаю свое состояние
<View>
//I want to immediately render this.state.userName
<Text>{this.state.userName}</Text>
<TextInput
onChangeText = {(noteText) => this.setState({noteText:noteText})}
value = {this.state.noteText}
/>
</View>
Мое состояние не будет отображаться, пока я не начну что-то печатать в своем TextInput. Любая идея, как я могу сделать немедленно?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


У вас есть два пути здесь.
Установить состояние по умолчанию,
constructor(props) {
super(props)
this.state = {
noteText: '',
userName:'Kevin',
}
this.changeState = this.changeState.bind(this);
}
Или звоните changeState в componentDidMount,
componentDidMount(){
this.changeState(); //bind this to changeState in constructor
}
Вы можете скорее использовать внутреннюю привязку своей функции внутри вашего конструктора или использовать функцию стрелки.
constructor(props) {
this.changeState = this.changeState.bind(this);
}
или
changeState = () => {
this.setState({ userName: "Kevin" });
};
Попробуйте простую закуску: https://snack.expo.io/@abranhe/change-state

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default class App extends Component {
state = { userName: '' };
changeState = userName => {
this.setState({ userName });
};
render() {
return (
<View style = {styles.container}>
<Text style = {styles.username}>{this.state.userName}</Text>
<Button title = "Abraham" onPress = {() => this.changeState('Abraham')} />
<Button title = "James" onPress = {() => this.changeState('James')} />
<Button title = "Mark" onPress = {() => this.changeState('Mark')} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
username: {
alignSelf: 'center',
marginBottom: 20,
},
});
Вы можете скорее сделать
changeState=()=>{}илиthis.changeState = this.changeState.bind(this)в своем конструкторе.