如何在React应用程序中创建唯一帐户

时间:2019-04-09 10:09:14

标签: reactjs user-interface web-applications

我正在制作一个React应用,您可以在其中以管理员身份登录并有机会手动添加帐户。我想按用户名使帐户唯一,但我不知道如何调用过去的用户名来与要注册的当前用户名进行比较。这是我到目前为止所做的:

  class GroupList extends Component {

constructor(props) {
    super(props);
    this.state = {groups: [], isLoading: true};
    this.remove = this.remove.bind(this);
}

componentDidMount() {
    this.setState({isLoading: true});

    fetch('api/groups')
        .then(response => response.json())
        .then(data => this.setState({groups: data, isLoading: false}));
}

async remove(id) {
    await fetch(`/api/group/${id}`, {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).then(() => {
        let updatedGroups = [...this.state.groups].filter(i => i.id !== id);
        this.setState({groups: updatedGroups});
    });
}

render() {
    const {groups, isLoading} = this.state;

    if (isLoading) {
        return <p>Loading...</p>;
    }

    const groupList = groups.map(group => {
        const username = `${group.username || ''} `;
        const password= `${group.password || ''}`;
        return <tr key={group.id}>
            <td style={{whiteSpace: 'nowrap'}}>{group.name}</td>
            <td>{username}</td>
            <td>{password}</td>

            <td>
                <ButtonGroup>
                    <Button  className="propreties" size="sm" color="primary" tag={Link} to={"/groups/" + group.id}>Edit</Button>
                    <Button className="propsss" size="sm" color="danger" onClick={() => this.remove(group.id)}>Delete</Button>
                </ButtonGroup>
                <Button className="props1" size="sm" color="success">Change User Role</Button>
            </td>
        </tr>
    });

}

}

导出默认GroupList;

这是编辑类:

class GroupEdit extends Component {

emptyItem = {
    name: '',
   username: '',
    password: '',

};

constructor(props) {
    super(props);
    this.state = {
        item: this.emptyItem
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

async componentDidMount() {
    if (this.props.match.params.id !== 'new') {
        const group = await (await fetch(`/api/group/${this.props.match.params.id}`)).json();
        this.setState({item: group});
    }
}

handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    let item = {...this.state.item};
    item[name] = value;

    this.setState({item});
}

async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/group', {
        method: (item.id) ? 'PUT' : 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(item),
    });
    this.props.history.push('/group');
}

0 个答案:

没有答案