React Native - 推送到数组后渲染

时间:2017-07-14 00:03:49

标签: javascript reactjs react-native

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

{{1}}

3 个答案:

答案 0 :(得分:1)

你所写的并不典型。快速解决方法是将逻辑移动到像

这样的渲染函数
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>

   )
 }

答案 1 :(得分:0)

您不应该使用生命周期调用来向数组添加元素。只需调用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> )

答案 2 :(得分:0)

返回this.arrayholder.map(image => {   返回(

<View style={styles.ImageContainer}>

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

  )

})