2016-02-28 87 views
0

我有一个ReactNative应用程序,它有一个返回JSON对象的getUserSession函数。我想调用这个函数,然后将setState设置为getUserSession的回调结果。ReactNative setState JSON对象

class AppContainer extends Component{ 
constructor(props){ 
super(props); 

    this.state = { 
     selectedTab: 'profile', 
    } 
} 

componentDidMount(){ 
    this.fetchData(); 

    this.setState({ 
     loggedIn: true, 
    }); 
} 

fetchData(){ 
    userService.getUserSessionData(function(result){ 
     // Console log function displays correct result 
     console.log(result); 
     this.setState({ 
     user: JSON.stringify(result), 
     }); 
    }) 
} 

render() { 
    let currentUser = this.state.user; 

    return (
    <TabBarIOS style={Theme.appContainer}> 
     <TabBarIOS.Item 
     title="Profile" 
     selected={this.state.selectedTab == "profile"} 
     <NavigatorIOS 
      initialRoute={{ 
      title: 'Profile', 
      component: Profile, 
      passProps: {data: currentUser} 
      }} /> 
     </TabBarIOS.Item> 

    </TabBarIOS> 
    ); 
    } 
}; 

module.exports = AppContainer; 

在fetchData的执行console.log功能呈现预期的行为,并显示我在想什么,但是在下一行不正确SETSTATE。

当通过在NavigatorIOS上使用PassProps传递状态时,子组件'Profile'不会接收道具并返回'undefined'。

我试图JSON.stringify()的结果,因为我认为的setState将允许JSON的字符串,但是这无法正常工作或

回答

0

我觉得this不再指向正确的参考。请尝试重写这样的功能,使用ES6可用的脂肪箭头语法:

fetchData(){ 
    userService.getUserSessionData((result) => { 
    console.log(result); 
    this.setState({ 
     user: JSON.stringify(result), 
    }); 
    }) 
} 
+0

谢谢,这似乎确实奏效。然而,我发现当加载应用程序时,它返回值为'undefined'。然后当我重新加载模拟器它回来了正确的值 – tmhn

+0

也许尝试在fetchData函数完成后设置登录状态? –

0

如何试图设置你的状态的默认值,即

this.state = { 
 
    user: '', 
 
    loggedIn: false, 
 
    etc:'', 
 
}