【发布时间】:2021-03-28 22:12:40
【问题描述】:
我正在尝试在我的 React Native 应用程序中创建一个简单的 Logout 从我的 Home.tsx 在正常登录之后和之后使用 Redux 将用户存储在我的 UserState 中。
实际上,当我调用 Logout 函数时出现错误,因为当我使用 dispatch 进行删除操作时,Navigator 会再次渲染,但我不明白为什么这会再次尝试渲染 Home.tsx,这会引发错误,因为只必须渲染 Home。 tsx 如果存在用户:
Navigator.tsx:(我把console.log放上来看看)
import React from 'react'
import { createStackNavigator } from '@react-navigation/stack'
import {connect} from 'react-redux'
import Login from '../Views/Login'
import Home from '../Views/Home'
const Stack = createStackNavigator();
const Navigator= (props) =>{
const {users} = props;
return (
<Stack.Navigator>
{console.log('Navigator here, '+users.current)}
{users.current ===null ?
(<>
<Stack.Screen name="Login" component={Login} options={{headerShown:false}}/>
</>)
: (<>
<Stack.Screen name="Home" component={Home} options={{headerShown:false}}/>
</>)
}
</Stack.Navigator>
);
}
const mapStateToProps=(state)=>{
const {users} = state;
return {users};
}
export default connect(mapStateToProps)(Navigator);
Home.tsx(我把 Console.log 放在了注销功能中)
import React from 'react'
import {Text, Container, Content, View, Button, Icon} from 'native-base'
import Styles from './Styles/HomeStyles'
import {connect} from 'react-redux'
import GeneralFooter from '../Components/GeneralFooter'
import {Auth} from '../Services/Auth/AuthService'
const Home =(props) => {
const {navigation, users} = props;
return(
<Container >
<Content >
<View style={Styles.content}>
<Text>Hola {users.current.id}</Text>
<Button onPress={()=>Logout(users.current.id)} >
<Icon name='menu' />
</Button>
</View>
</Content>
<GeneralFooter />
</Container>
);
async function Logout(id:string){
console.log('Function start');
await Auth.LogoutUser(id, props);
console.log("NOW USERS: "+users.current);
navigation.navigate('Login');
}
}
const mapStateToProps=(state)=>{
const {users} = state;
return {users};
}
export default connect(mapStateToProps)(Home);
AuthService.tsx(操作返回:{type : 'DELETE_USER',id}):
import {UserActions} from '../../Store/Actions/UserActions'
export const Auth={
LoginUser,
LogoutUser
}
async function LoginUser(...){
//code...
}
async function LogoutUser(id: string, props: any){
await props.dispatch(UserActions.Delete(id));
}
UserReducer.tsx:
const Initial_State={
current:null
}
export function UserReducer(state=Initial_State, action:any){
switch (action.type){
case 'ADD_USER':
return{
...state,
current: action.user
};
case 'DELETE_USER':
return{
...state,
current: null
};
default:
return state;
}
}
而错误结果是:
你可以看到Navigator如何再次渲染并且users.current为null(在函数启动和调度之后),但是在函数显示users.current的值之后;只有我需要从状态中删除用户并返回到 Login.tsx。
【问题讨论】:
标签: javascript react-native redux async-await navigator