Javascript 在推送到阵列后反应本机渲染

Javascript 在推送到阵列后反应本机渲染,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在映射要在React Native中呈现的数组。在一个事件按钮上,按下我想添加和对象到数组中,并在屏幕上呈现。我正在触发生命周期功能,但不确定是否需要它们,或者如何有效地利用它们。任何帮助都将不胜感激 class Home extends Component { constructor(props) { super(props) this.state = { data: '', text: '', submitted: false,

我正在映射要在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>

  )
 }
}

您不应该使用生命周期调用将元素添加到数组中。只需调用setState,它就会自动重新启动

试试这个

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

你写的东西不典型。快速修复方法是将逻辑移动到渲染函数,如

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() {

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

      </View>

   )
 }

返回this.arrayholder.mapimage=>{ 返回

<View style={styles.ImageContainer}>

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

  )

}

是的,我最初有这个功能,它也不会更新onPress事件的屏幕。您是否尝试过导出该功能?比如OnButtonPress==>。。。。在函数中的onPress上调用它?不过,别忘了这个。我有一种感觉,这可能与map函数的不同有关。如果这不起作用,请看ListView:我修复了这个问题,并在count语句后添加了逗号,仍然没有呈现,this.state.arr.push上会抛出一个错误,我相信,因为this.state在这种情况下被视为不可变的。我将检查它,并使用您的建议,不会更改任何内容