繁体   English   中英

反应随机改变的本机状态值

[英]react native state value changing randomly

第一个console.log(this.state.dataSource)的数据块给了我

  [ { date: '2017-07-13',
      images: 
       [ { image: 'assets-library://asset/asset.JPG?id=8855847A-7157-4D04-8E71-43746BED3E2E&ext=JPG',
           selected: false } ],
      key: 0 }]

第二个console.log(this.state.dataSource)给我数据blob:

  [ { date: '2017-07-13',
      images: 
       [ { image: 'assets-library://asset/asset.JPG?id=8855847A-7157-4D04-8E71-43746BED3E2E&ext=JPG',
           selected: true } ],
      key: 0 }]

如您所见,我从未在此函数中使用setState来更改this.state.dataSource的值,那怎么回事,我的函数也正在影响this.state.dataSource的值? 由于这一行,似乎可以直接操纵该状态值

tempImages[index].selected = !tempImages[index].selected

_

setSelected(date,index,value){
    console.log(this.state.dataSource)
    let tempArray = data
    let tempImages = []
    for(var i in tempArray){
        if(tempArray[i].date == date){
            tempImages = tempArray[i].images
        }
    }
    console.log(tempImages)
    tempImages[index].selected = !tempImages[index].selected
    console.log(tempImages)
    console.log(this.state.dataSource)
}

编辑:

sortPhotos(value){
    let tempArray = []
    for(var i in value){
        let found = false
        for(var e in tempArray){
            if(tempArray[e].date == moment(value[i].node.timestamp*1000).format('YYYY-MM-DD')){
                found = e
            }
        }
        if(!found){
            tempArray.push({
                date: moment(value[i].node.timestamp*1000).format('YYYY-MM-DD'),
                images: [{image: value[i].node.image.uri, selected: false}],
                key: tempArray.length
            })
        }else{
            let images = tempArray[found].images
            images.push({
                image: value[i].node.image.uri,
                selected: false
            })
            tempArray[found].images = images
        }
    }
    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(tempArray),
        dataSourceClean: tempArray,
        loaded: true
    })
}

setSelected(date,index,value){
    let tempArray = this.state.dataSourceClean
    let tempImages = []
    for(var i in tempArray){
        if(tempArray[i].date == date){
            tempImages = tempArray[i].images
        }
    }
    tempImages[index].selected = !tempImages[index].selected
    console.log(this.state.dataSource)
}

您正在使用数组克隆dataSource ,该克隆将使用对tempArray引用tempArray ,因此,无论何时对tempArray进行更改,这些更改都会反映在dataSource 您必须在代码中执行以下操作:

dataSource: this.state.dataSource.cloneWithRows([...tempArray])

我们用做[...tempArray]是我们传递的一个副本tempArray这是没有关联的方式tempArray ,你所做的任何更改tempArray不会反映dataSource

PS

  • 在Javascript字符串中,使用值(新副本)分配数字,而将数组,对象,日期指定为引用(指向同一对象的点)。
  • ES6中引入了...是Spread运算符。 您可以了解更多有关它在这里传播运营商

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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