0

When i press the <TouchableOpacity> Button, i want the value 'abc' to be appended to the array selectedTags and then <Text> {this.list()} </Text> will print out my array.
But now when i press the Button, nothing display out.

Can anybody know what is the problem with my code?

export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          selectedTags: []
        }
  }

  list() {
  return this.state.selectedTags.map(function(tags, i){
    return(
      <View key={i}>
        <Text>{tags.name}</Text>
      </View>
    );
  });
}

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity  onPress={() => this.state.selectedTags.push('abc')} key = {1} style={styles.buttonContainer}>
              <Text style={styles.buttonText}> Button </Text>
         </TouchableOpacity>

          <Text> {this.list()} </Text>
      </View>
    );
  }
}

2 Answers 2

1

This is because you never call setState, which would trigger re-render of your component.

instead of using:

onPress={() => this.state.selectedTags.push('abc')}

try:

onPress={() => this.setState({selectedTags: this.state.selectedTags.concat('abc')})}
Sign up to request clarification or add additional context in comments.

2 Comments

why use concat instead of push??
because push change the array but does not return anything. concat does not change the array but return a new array with the value provided added at the end of the new array. So in order to assign the new selectedTags attribute I need to use concat
1

The function list only push data in array but does not rerender the view, todo so you have to use setState or forceUpdate.

You can implement the onpress function like this.

onPress = () =>{
  this.state.selectedTags.push("abc");
  this.setState({selectedTags : this.state.selectedTags});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.