检查用户是否存在于用户数组中

Checking if an user exists in an array of users

我正在尝试使用 React 和 Redux 创建用户登录系统。我使用如下模型数据:

const users = [
{
    "id":1,
    "username":"user1",
    "email":"user@hotmail.com",
    "password":"1527393"
},
{
    "id":2,
    "username":"user2",
    "email":"user2@hotmail.com",
    "password":"1527393"
}
];


export default users;

此数据是通过默认状态添加到商店中的。我的 store.js 文件如下:

    import {createStore, compose} from 'redux';
import rootReducer from '../reducers/index';

import userLoginReducer from '../data/users';

const defaultState = {
    userLoginReducer
};

export default function configureStore() {
    return createStore(
        rootReducer,
        defaultState,
        compose(
            window.devToolsExtension ? window.devToolsExtension() : f => f //we use this line for chrome redux extension
        )
    );
}

我连接到 redux 的登录组件是:

    import React from 'react';
import LoginForm from './loginForm';

import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actionCreators from '../../actions/actionCreators';

class Login extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            loginData: {
                username: '',
                password: ''
            },
            errors: {}
        };

        this.buttonClickHandle = this.buttonClickHandle.bind(this);
        this.loginHandle = this.loginHandle.bind(this);
    }

    loginHandle(event) {
        let field = event.target.name;
        let value = event.target.value;

        let loginData = this.state.loginData;
        loginData[field] = value;

        this.setState({loginData: loginData});
    }

    buttonClickHandle(event) {
        event.preventDefault();
        this.props.actions.userLoginSuccess(this.state.loginData.username, this.state.loginData.password);

        if (this.props.users.length > 0) {
            console.log("User exists. Go to the login page");
        } else {
            console.log("User doesn't exists. Show error message");
        }
    }

    render() {
        const language = this.props.currentLanguage;
        return (
            <div className="container">
                <div className="row">
                    <p className="col-lg-4 col-xs-12 col-md-4 loginTitle noPadding">{language.loginTitle}</p>
                    <div className="col-lg-8 col-xs-12 col-md-8 loginForm noPadding">
                        <LoginForm currentLanguage={language} onClick={this.buttonClickHandle}
                                   onChange={this.loginHandle} errors={this.state.errors}/>
                    </div>
                </div>
            </div>
        );
    }
}

function mapStateToProps(state, ownProps) {
    return {
        users: state.userLoginReducer
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionCreators, dispatch)
    };
}


export default connect(mapStateToProps, mapDispatchToProps)(Login);

在页面加载时,我从数据文件中获取了这两个用户。没关系。

在登录组件的 buttonClickHandle 函数中,我使用用户名和密码调用了一个操作,我想检查来自 reducer 的 returned 数组是否为空。如果它是空的,我会更新 state.errors,如果它不是空的,我会重定向到欢迎页面。

在 reducer 中,我过滤数据并检查具有 action.username 的用户是否存在,并且我 return 该数组到我的登录组件。

reducer代码如下:

    export default function userLoginReducer(state = [], action) {
    switch(action.type){
        case "USER_LOGIN_SUCCESS":
            return [...state.filter(user => user.username === action.username)];
        default:
            return state;
    }
}

但是没有用。

如果我在页面加载时使用用户名 user1 提交表单,它可以工作,但是当我在页面加载时提交它也可以工作,例如 user18。

有什么建议吗?

问题是检查用户是否存在的代码不正确。

你有

if (this.props.users.length > 0) {
 console.log("User exists. Go to the login page");
} else {
 console.log("User doesn't exists. Show error message");
}

但是,假设您检查包含两个对象的 users 对象,this.props.users.length > 0 将始终 return true。即使您检查不在 users.

中的用户

您需要使用 indexOfincludes 或其他方式添加一种检查实际用户名的方法。例如,这会起作用:

const { users } = this.props;

if (users.length > 0 && users.find(user => user.username === this.state.loginData.username)) {
 console.log("User exists. Go to the login page");
} else {
 console.log("User doesn't exists. Show error message");
}