我正在映射要在React Native中渲染的数组。在事件(按按钮)上,我想向数组添加对象,并将其呈现在屏幕上。我正在触发生命周期功能,但是不确定是否需要此功能或如何有效利用它们。任何帮助将不胜感激!

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>

  )
 }
}

最佳答案

您写的不是典型的。一个快速的解决方法是将逻辑移至渲染函数,例如

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> )
    })
}


然后在render()中调用该函数

render() {

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

      </View>

   )
 }

关于javascript - React Native-推送到数组后渲染,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45092655/

10-10 00:39
查看更多