我有一个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的字符串,但是这无法正常工作或
谢谢,这似乎确实奏效。然而,我发现当加载应用程序时,它返回值为'undefined'。然后当我重新加载模拟器它回来了正确的值 – tmhn
也许尝试在fetchData函数完成后设置登录状态? –