I am adding items to the array. Items are added but not displayed the last item added. For example, array [1,2,3,4] prints 123 but does not display 4.
export default class App extends Component {
constructor(props){
super(props);
this.state = {
input : [],
Array:[],
}
}
addTextInput = () => {
this.state.Array.push(this.state.input.toString());
}
handleText=(text)=>{
this.setState({input:text});
}
render() {
return (
<View>
<TextInput
onChangeText={(text) =>this.handleText(text)}
value={this.input} />
<Button title='Add Item' onPress={() => this.addTextInput()} />
{this.state.Array.map((item) => {
<Text>{item}</Text>
}
</View>
);
}
}
CodePudding user response:
You are attempting to mutate the state directly in addTextInput
, which is not allowed in React. You must update the array via setState
, which will then trigger a render, which will display the new value:
addTextInput = () => {
this.setState((prevState) => ({ Array: [...prevState.Array, this.state.input.toString())) });
}