问题是指变量的范围

时间:2019-08-29 15:44:51

标签: react-native

如何从外层方法获取变量

尝试在React-Native App的外层使用变量

updateCheckBox() {
        Constants.TABS.map((item) => {//Constants.TABS is an array
                AsyncStorage.getItem(item)//using item as key to fetch from AsyncStorage
                .then((res) => {
                    if(res == 1) {
                        //debugged here, item was undeined. but i need setState here with item as key. How should i get item here.
                        this.setState({item: true}) // I need to get the item here, but it show undefined
                    } else {
                        this.setState({item:false}) // I need to get the item here, but it show undefined
                    } 
                })
        })
    }

//我需要在这里获取商品,但显示为未定义

2 个答案:

答案 0 :(得分:1)

您需要将item包裹在[]中,以将其用作key的{​​{1}}。像这样:

property

答案 1 :(得分:0)

最后,我发现这段代码没有问题,问题是

updateCheckBox() {
    Constants.TABS.map((item) => {
            let key = item
            AsyncStorage.getItem(key)
            .then((res) => {
                console.log(item, "item is here", res); //item is  visible here
                console.log(key) //key is all always undefined 
                if(res == 1) {
                    this.setState({item: true}) 
                } else {
                    this.setState({item:false}) 
                } 
            })
    })
}

键然后在方法中不可见,我无法解释,但是总的来说,我的代码有效。