如何使用React Native在会话中存储值?

时间:2017-09-07 07:36:40

标签: javascript session react-native asyncstorage

我已使用index.js在用户注册(AsyncStorage.setItem)处将位置设置为会话变量。我试图在Profile.js中访问此会话变量。但是当我试图打印会话变量(位置)时,没有任何问题。以下是我的代码。我做错了什么?请帮忙

index.js

AsyncStorage.setItem('location').then((location) =>{
            this.setState({ location: location })
        })

Profile.js

fetch('http://loaclhost/apps/requirement.php',{
        method:'POST',
        headers: {
            'Accept':'application/json' ,
        },
        body: JSON.stringify({
            location:this.state.location,   
        })
    }).then( () =>
    {

        response => response.json();
    AsyncStorage.getItem('location').then((location) => {
        this.setState({location: location})
    })

    render(){
            return(
            <Container>
             <View>
            <TextInput 
        value={this.state.loctaion} />
             </View>
            </Container>
        );
    }

1 个答案:

答案 0 :(得分:0)

这可能会对你有帮助,

<强> index.js

AsyncStorage.setItem('location_key', 'location_value').then((location) =>{
    this.setState({ location: location })
})

<强> Profile.js

var getLocation = function(){
    return AsyncStorage.getItem('location_key')
}

var fetchCall = function(location){
    return fetch('http://loaclhost/apps/requirement.php',{
        method:'POST',
        headers: {
            'Accept':'application/json' ,
        },
        body: JSON.stringify({
            location: location, //Resolved location
        })
    })
}


function fetchRequest(){

    getLocation()
    .then(fetchCall)
    .then((response) => {
        //Response handling
    })
}