简体   繁体   中英

React Native - Rendering after pushing to array

I'm mapping an array to be rendered in React Native. On an event (button press) I want to add and object to the array and it be rendered on the screen. I am getting the lifecycle functions to trigger, but not sure if they are needed for this or how to utilize them effectively. Any help would be greatly appreciated!

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: '',
      text: '',
      submitted: false,
      count: 1,
      arr: [
        {
          key: 1,
          text: "text1"
       },
     ],
   }

buttonsListArr = this.state.arr.map(info => {
  return (
  <View style={styles.container}>
    <Text key={info.key}>{info.text}</Text>
    <Button title='Touch' onPress={() => {
        this.setState({count: this.state.count + 1})
     }}/>
 </View> )
})

}

shouldComponentUpdate = () => {
    return true;
}

componentWillUpdate = () => {
    this.state.arr.push({key: this.state.count, text: 'text2'})
}

render() {

  return (
  <View style={styles.container}>
    {buttonsListArr}

  </View>

  )
 }
}

What you've written is not typical. A quick fix is to move the logic to a render function like

constructor(props) {
.
.
    this.renderText = this.renderText.bind(this)
}

renderText() {
    return this.state.arr.map(info => {
        return (
            <View style={styles.container}>
                <Text key={info.key}>{info.text}</Text>
                <Button title='Touch' onPress={() => {
                    this.setState({count: this.state.count + 1})
                }}/>
            </View> )
    })
} 

then call the function within the render()

render() {

  return (
      <View style={styles.container}>
          {this.renderText()}

      </View>

   )
 }

You shouldn't be using a lifecycle call to add an element to an array. Simply call setState and it will rerender itself!

Try this.

<View style={styles.container}>
    <Text key={info.key}>{info.text}</Text>
    <Button title='Touch' onPress={() => {
        this.setState({
            count: this.state.count + 1
            arr: this.state.arr.push({key: this.state.count, text: 'text2'})
        })
     }}/>
 </View> )

return this.arrayholder.map(image => { return (

<View style={styles.ImageContainer}>

<Image style={styles.ImageContainer} source={image} />
  </View>

  )

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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