共有三个屏幕,分别是Index.tsx,Profile.tsx,Login.tsx。 我尝试去登录以设置AsyncStorage,然后返回到Profile,使用this.state.member从AsyncStorage获取以切换Profile中的组件。但是现在我只能以这种方式返回索引然后进行概要分析,这样我可以在概要文件中更改子组件
我之前通过使用react-navigation createSwitchNavigator()做到了这一点。但现在 我尝试在componentDidMount()
中使用this.setState({member:(AsyncStorage.getItem(“ member”)的结果)?AsyncStorage.getItem(“ member”):undefined})在Profile中重新呈现这是案件的代码,https://gist.github.com/sanhuang/4526dbd00051695c80b7b36dd7230ef8
export default class ProfileSreen extends Component {
constructor(props) {
super(props)
this.state = {
isLoading: true,
isSignIn: false,
member: undefined
}
this._getMemberStorage = this._getMemberStorage.bind(this);
}
componentDidMount() {
this._getMemberStorage();
}
async _getMemberStorage(): Promise<void> {
try{
// let member = null;
let member = await ExStorage.getItem("member");
// console.log(member);
if ( member !== null ){
await this.setState({
member,
isSignIn: true
});
}else{
await this.promisedSetState({
member: null,
isSignIn: false
});
}
await this.promisedSetState({
isLoading: false
});
return true;
}catch(e) {
console.error(e);
}
}
promisedSetState = (newState) => {
return new Promise((resolve) => {
this.setState(newState, () => {
resolve()
});
});
}
protected _renderLogin() {
return (
<ListItem>
<Button small rounded
onPress={() => {
this.props.navigation.navigate('Profile_Login');
}}
>
<Text>Login</Text>
</Button>
</ListItem>
)
}
protected _renderMember() {
return (
<ListItem>
<Body>
<H2>{this.state.member.cmt} {this.state.member.unit}{this.state.member.name},您好</H2>
<Text note>xxx</Text>
</Body>
</ListItem>
)
}
protected render() {
let infocoms = null;
if (this.state.isLoading ) {
return (
<L.PageLoading />
)
}else{
if (this.state.isSignIn) {
infocoms = this._renderMember();
} else {
infocoms = this._renderLogin();
}
return (
<Root>
<Container>
<Content>
<List>
{infocoms}
</List>
<Settings />
</Content>
{<L.IFooter />}
</Container>
</Root>
);
}
}
}
即使我登录,结果也始终呈现_renderLogin()
答案 0 :(得分:0)
您是否确实从登录请求中看到有效的member
值?
此外,您无需在setState
之前等待:
await this.setState({
member,
isSignIn: true
});
这可能会导致意外情况。