如何在React中使用sequelize获取用户列表?

时间:2019-05-21 06:41:03

标签: javascript node.js reactjs sequelize.js

我想使用续集获取表的用户数据。 正如我在想的那样,详细信息如下:

  1. 注册动作类型,动作创建者和简化器
  2. 从DirectoryContainer.js调用getUserList API
  3. 将表的用户数据显示到AsyncSelectInput组件

但是我迷路了。我该怎么办? 这是可疑的源代码。

store / modules / directory.js

import { createAction, handleActions } from "redux-actions";

import { Map } from "immutable";
import { pender } from "redux-pender";
import * as api from "lib/api";

// action types
const SHARED_LIST = "directory/SHARED_LIST";
const PRIVATE_LIST = "directory/PRIVATE_LIST";
const NOTE_LIST = "directory/NOTE_LIST";
const USER_LIST = "directory/USER_LIST";

const CREATE_FOLDER="directory/CREATE_FOLDER";
const DELETE_FOLDER="directory/DELETE_FOLDER";
const SHARED_FOLDER="directory/SHARED_FOLDER";
const UPDATE_FOLDER="directory/UPDATE_FOLDER";

const CREATE_NOTE="directroy/CREATE_NOTE";
const UPDATE_NOTE="directory/UPDATE_NOTE";
const DELETE_NOTE="directory/DELETE_NOTE";
const SET_NOTE="directory/SET_NOTE";
const SET_FOLDER="directory/SET_FOLDER";


// action creators
export const getSharedList = createAction(SHARED_LIST, api.getSharedList);
export const getPrivateList = createAction(PRIVATE_LIST, api.getPrivateList);
export const getNoteList = createAction(NOTE_LIST, api.getNoteList);
export const getUserList = createAction(USER_LIST);

export const createFolder = createAction(CREATE_FOLDER, api.createFolder);
export const deleteFolder =  createAction(DELETE_FOLDER, api.deleteFolder);
export const sharedFolder = createAction(SHARED_FOLDER,api.sharedFolder);
export const updateFolder = createAction(UPDATE_FOLDER, api.updateFolder);

export const createNote = createAction(CREATE_NOTE, api.createNote);
export const updateNote = createAction(UPDATE_NOTE, api.updateNote);
export const deleteNote = createAction(DELETE_NOTE, api.updateNoteStatusDeleted);
export const setNote = createAction(SET_NOTE);
export const setFolder = createAction(SET_FOLDER);


// initial state
const initialState = Map({
    sharedList: [],
    privateList: [],
    noteList: [],
    userList: [],
    folder:null,
    note:null
});


// reducer
export default handleActions(
    {
            ...pender(
            {
                type: [PRIVATE_LIST],
                onSuccess: (state, action) => {
                    const { data: privateList } = action.payload.data;
                    return state.set("privateList", privateList);
                }
            }),
            ...pender(
            {
                type: [SHARED_LIST],
                onSuccess: (state, action) => {
                    const { data: sharedList } = action.payload.data;
                    return state.set("sharedList", sharedList); 
                }
            }),
            ...pender(
            {
                type: [NOTE_LIST],
                onSuccess: (state, action) => {
                    const { data: noteList } = action.payload.data;
                    return state.set("noteList", noteList);
                }
            }),
            ...pender(
            {
                type: [USER_LIST],
                onSuccess: (state, action) => {
                    const { data: userList } = action.payload.data;
                    console.log("userList ...pender", userList);
                    return state.set("userList", userList);
                }
            }),
            [SET_NOTE]: (state, action) => {
                const { payload: note } = action;
                return state.set('note', note);
            },
            [SET_FOLDER]: (state, action) => {
                const { payload: folder } = action;
                console.log("SET_FOLDER2",folder);
                return state.set('folder', folder);
            },
    },
    initialState
);

container / DirectoryConatiner.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as directoryActions from "store/modules/directory";
import Directory from "components/main/Directory";
import {withRouter} from 'react-router-dom';

import socketio from 'socket.io-client';
const socket=socketio.connect('http://192.168.0.68:4000');


class DirectoryContainer extends Component {
    updateFolderList = () => {
        const { DirectoryActions, id } = this.props;
        if (id) {
            DirectoryActions.getPrivateList(id);
            DirectoryActions.getSharedList(id);
        }
    }

    createFolder=async(user_id,folder_name)=>{
        await this.props.DirectoryActions.createFolder(user_id, folder_name);
        socket.emit('updateFolderList',{ msg:'createFolder'});
    }
    sharedFolder=async(user_id,folder_id,permission)=>{
        await this.props.DirectoryActions.sharedFolder(user_id,folder_id,permission);
        socket.emit('updateFolderList',{ msg:'sharedFolder'});
        //
        socket.emit('userList', { msg: 'userList' });
    }

    deleteFolder=async(folder_id) => {
        await this.props.DirectoryActions.deleteFolder(folder_id);
        await this.props.DirectoryActions.getNoteList(0);
        socket.emit('updateFolderList',{ msg:'deleteFolder'});
    }

    updateFolder=async(folder_id, folder_name) => {
        await this.props.DirectoryActions.updateFolder(folder_id, folder_name);
        socket.emit('updateFolderList',{ msg:'updateFolder'});
    }
///////////////////////////////---------------------NOTE----------------------//////////////////////////////

    // Get user list when opened AskShareModal
    userList = () => {
        const { DirectoryActions } = this.props;
        console.log('getUserList in DirectoryContainer: ');
        DirectoryActions.getUserList();
    }

    updateNoteList = () => {
        const { DirectoryActions, folder } = this.props;
        console.log('updateNoteList::', folder);
        if(folder)
            DirectoryActions.getNoteList(folder);
    }

    createNote=async(folder_id,note_name)=>{
        const {DirectoryActions}=this.props;
        await DirectoryActions.createNote(folder_id,note_name);
        socket.emit('updateFolderList',{ msg:'createNote'});
        socket.emit('updateNoteList',{ msg:'createNote'});
    }

    updateNote=async(ids, note_name) => {
        const {DirectoryActions} = this.props;
        await DirectoryActions.updateNote(ids.note_id, note_name);
        socket.emit('updateNoteList',{ msg:'updateNote'});

    }

    deleteNote = async(ids) => {
        const {DirectoryActions} = this.props;
        await DirectoryActions.deleteNote(ids.note_id);
        // socket.emit( event name to the server, data )
        socket.emit('updateFolderList', { msg: 'deleteNote' });
        socket.emit('updateNoteList', { msg: 'deleteNote' });

        DirectoryActions.setNote(null);
    }


    setNote=(uuid)=>{
        const {DirectoryActions} = this.props;
        DirectoryActions.setNote(uuid);
    }
    setFolder=(folder_id)=>{
        const {DirectoryActions} = this.props;

        DirectoryActions.setFolder(folder_id);
        DirectoryActions.getNoteList(folder_id);

    }

    componentWillMount(){
        setTimeout(()=>{
            if(this.props.id){
                this.updateFolderList();
                }else{
                    this.props.history.push('/');
                }
        }, 1000);

    }
    componentDidMount(){
        socket.on('updateFolderList',(obj)=>{
            this.updateFolderList();
        })
        socket.on('updateNoteList',(obj)=>{
            this.updateNoteList();
        })
    }

    render() {
        const { sharedList, privateList, noteList, userList, id} = this.props;
        const { createFolder, sharedFolder, deleteFolder, updateFolder, updateNote, createNote, deleteNote, setNote, setFolder} = this;
        return (
            <div style={{ display: "flex" }}>
                <Directory sharedList={sharedList} privateList={privateList} noteList={noteList}
                           userList={userList} user_id={id}
                           createFolder={createFolder} updateFolder={updateFolder}
                           deleteFolder={deleteFolder} sharedFolder={sharedFolder}
                           createNote={createNote} updateNote={updateNote} 
                           deleteNote={deleteNote} setNote={setNote} setFolder={setFolder} />
            </div>
        );
    }
}

export default connect(
    (state) => ({
        sharedList: state.directory.get("sharedList"),
        privateList: state.directory.get("privateList"),
        noteList: state.directory.get("noteList"),
        userList: state.directory.get("userList"),
        folder: state.directory.get("folder"),
        id: state.user.get("id"),
    }),
    (dispatch) => ({
        DirectoryActions: bindActionCreators(directoryActions, dispatch)
    })
)(withRouter(DirectoryContainer));

components / main / Editor / Directory.js

import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import List from "@material-ui/core/List";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import Collapse from "@material-ui/core/Collapse";
import { Menu, ExpandMore, ExpandLess, CreateNewFolder, FolderShared, Delete, Folder, Share, Lock, Create, 
    GroupAdd, ChevronLeft, ChevronRight, NoteAdd} from "@material-ui/icons";
import OneInputModal from "../modal/OneInputModal";
import AskShareModal from '../modal/AskShareModal';
import NoticeModal from '../modal/NoticeModal';

const drawerWidth = 250;

const styles = theme => ({
    root: {
        display:'flex',
    },
    menuButton: {
        marginRight: 3.5
    },
    drawer: {
        width: drawerWidth,
        flexShrink: 0,
    },
    drawerOpen: {
        height: 'calc(100vh - 6rem)', 
        position:'unset',
        width: drawerWidth,
        transition: theme.transitions.create("width", {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.enteringScreen
        }),
    },
    drawerClose: {
        height: 'calc(100vh - 6rem)', 
        transition: theme.transitions.create("width", {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen
        }),
        overflowX: "hidden",
        width: theme.spacing.unit * 5 + 1,
        [theme.breakpoints.up("sm")]: {
            width: theme.spacing.unit * 7 + 1
        }
    },
    SubDrawerOpen: {
        height: 'calc(100vh - 6rem)', 
        position:'unset',
        width: drawerWidth,
        transition: theme.transitions.create("width", {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.enteringScreen
        }),
    },
    SubDrawerClose: {
        display: 'none'
    },
    toolbar: {
        display: "flex",
        justifyContent: "flex-end",
    },
    paper: {
        position : "unset",
    },
    drawerOverflow: {
        overflowX: "hidden",
    },
    list : {
        overflowX: "hidden",
        overflowY: "auto",
    },

});

/** @param1 types of modal, @param2 icon, @param3 title of modal, @param4 content of modal, @param5 button */
const createFolderModalData = ["oneInputModal", 'folder-plus', '공유 폴더 생성', '생성할 폴더명을 입력해주세요.', '생성'];
const shareFolderModalData = ["askShareModal", 'folder-plus', '공유 폴더 초대', '해당 폴더로 초대할 직원을 선택해주세요.', '초대'];
const deleteFolderModalData = ["noticeModal", 'trash-alt', '공유 폴더 삭제', '공유 폴더를 정말 삭제하시겠습니까?', '삭제'];
const updateFolderModalData = ["oneInputModal", 'file-signature', '폴더 이름 수정', '수정할 폴더명을 새로 입력해주세요.', '수정'];

const createNoteModalData = ["oneInputModal", 'file-alt', '노트 생성', '생성할 노트명을 입력해주세요.', '생성'];
const deleteNoteModalData = ["noticeModal", 'trash-alt', '노트 삭제', '노트를 정말 삭제하시겠습니까?', '삭제'];
const updateNoteModalData = ["oneInputModal", 'file-signature', '노트 이름 수정', '수정할 노트명을 새로 입력해주세요.', '수정'];

const exportNoteModalData = ["oneInputModal", 'file-pdf', '노트 내보내기', '해당 내용을 PDF 파일로 내보내겠습니까?', '확인'];
const lockedNoteModalData = ["noticeModal", 'file-alt', '노트 생성', '생성할 노트명을 입력해주세요.', '생성'];


const modalList = [
    createFolderModalData,  // modalList[0]
    shareFolderModalData,   // modalList[1]
    deleteFolderModalData,  // modalList[2]
    updateFolderModalData,  // modalList[3]

    createNoteModalData,    // modalList[4]
    deleteNoteModalData,    // modalList[5]
    updateNoteModalData,    // modalList[6]

    exportNoteModalData,    // modalList[7]
    lockedNoteModalData     // modalList[8]
]


class Directory extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            SubOpen: false,
            public_navigationOpen: false,
            private_navigationOpen: false,

            folder_id : 0,
            folder_name : '',
            note_id : 0,
            note_name: '',

            oneInputModal: false,
            noticeModal: false,
            selectModal: false,
            askShareModal: false,

            modalAction:null,

            modal_text:'',
            modal_data:0,
            modal_icon: '',
            modal_title: '',
            modal_content: '',
            btn_name:'', 

        };
        this.handleUserData = this.handleUserData.bind(this);
    }

    handlePublicClick = () => {
        this.setState(state => ({
            public_navigationOpen: !state.public_navigationOpen
        }));
    };
    handlePrivateClick = () => {
        this.setState(state => ({
            private_navigationOpen: !state.private_navigationOpen
        }));
    };
    handleDrawerOpen = () => {
        this.setState({ open: true });
    };
    handleDrawerClose = () => {
        this.setState({ open: false });
        this.setState({ SubOpen: false });
        this.setState({ private_navigationOpen: false });
        this.setState({ public_navigationOpen: false });
    };
    handleSubDrawerOpen = () => {
        this.setState({ SubOpen: true });
    };
    handleSubDrawerClose = () => {
        this.setState({ SubOpen: false });
    };
 /** [main navigation] handling folder modal */


    handleSetModal=(array,action,data,text) => {
        if (modalList[1] === array) {
            console.log('text ', text);
            this.handleUserData();
        }
        this.setState({
            [array[0]]: true,
            modal_icon: array[1],
            modal_title: array[2],
            modal_content: array[3],
            btn_name: array[4],
            modalAction:action,
            modal_data:data,
            modal_text:text
        });
    }
    handleUnSetModal=(type)=>{
        this.setState({
            [type]: false
        });
    }

    handleFolderData = (folder_id, folder_name) => {
        this.setState({folder_id: folder_id , folder_name: folder_name });
        this.props.setFolder(folder_id);
    };
    handleNoteData = (note_id, note_name,note_content) => {
        this.setState({note_id: note_id , note_name: note_name });
        this.props.setNote(note_content);
    };
    handleUserData = () => {
        // this.setState({
        //     userList: this.props.userList
        // });
        // this.props.userList();
        console.log(this.props);
    }

    render() {
        const { classes, theme,
             sharedList = [], privateList = [], noteList = [], userList = ['홍길동', '생림'],
             user_id = 0, folder_id = 0,
             createFolder, sharedFolder, deleteFolder, updateFolder,
             createNote, updateNote, deleteNote } = this.props;

        return (
            <div className={classes.root}>
                <Drawer 
                    variant="permanent"
                    className={classNames(classes.drawer, {
                        [classes.drawerOpen]: this.state.open,
                        [classes.drawerClose]: !this.state.open
                    })}
                    classes={{
                        paper: classNames(classes.paper, {
                            [classes.drawerOpen]: this.state.open,
                            [classes.drawerClose]: !this.state.open,
                        })
                    }}
                    open={this.state.open}
                >
                    <div className={classes.toolbar}>
                        {this.state.open ? (
                            <div>
                                <OneInputModal 
                                             visible={this.state.oneInputModal}
                                             onCancel={(e)=>this.handleUnSetModal('oneInputModal')}
                                             onConfirm={this.state.modalAction}
                                             modal_icon={this.state.modal_icon}
                                             modal_title={this.state.modal_title}
                                             modal_content={this.state.modal_content}
                                             btn_name={this.state.btn_name}
                                             id={this.state.modal_data}
                                             text={this.state.modal_text}
                                             />

                                <NoticeModal 
                                            visible={this.state.noticeModal}
                                            onCancel={(e)=>this.handleUnSetModal('noticeModal')}
                                            onConfirm={this.state.modalAction}
                                            modal_icon={this.state.modal_icon}
                                            modal_title={this.state.modal_title}
                                            modal_content={this.state.modal_content}
                                            btn_name={this.state.btn_name} 
                                            id={this.state.modal_data}
                                            />


                                <AskShareModal
                                            visible={this.state.askShareModal}
                                            onCancel={(e)=>this.handleUnSetModal('askShareModal')}
                                            onConfirm={this.state.modalAction}
                                            modal_icon={this.state.modal_icon}
                                            modal_title={this.state.modal_title}
                                            modal_content={this.state.modal_content}
                                            btn_name={this.state.btn_name} 
                                            folder_id={this.state.folder_id}
                                            userList={userList} />

                                <IconButton>
                                    <CreateNewFolder color="primary" onClick={(e)=>this.handleSetModal(modalList[0],createFolder,user_id, '')}/>
                                </IconButton>

                            {/* {userList.map(item => ( */}
                                <IconButton>   
                                    <GroupAdd color="primary" onClick={(e) => this.handleSetModal(modalList[1], sharedFolder, folder_id, userList)} />
                                </IconButton>
                            {/* ))} */}

                                <IconButton
                                    onClick={this.handleDrawerClose}
                                    className={classNames(classes.menuButton)}
                                >
                                <ChevronLeft />
                                </IconButton>
                            </div>
                        ) : (
                            <IconButton
                                onClick={this.handleDrawerOpen}
                                className={classNames(classes.menuButton)}
                            >
                                <Menu />
                            </IconButton>
                        )}
                    </div>
                    <Divider />
                    <List className={classes.list}>
                        <ListItem 
                            button
                            onClick={event => {
                                this.handleDrawerOpen();
                                this.handlePublicClick();
                            }}
                        >
                            <ListItemIcon>
                                <FolderShared />
                            </ListItemIcon>
                            <ListItemText primary="public" />
                            {this.state.public_navigationOpen ? (
                                <ExpandLess />
                            ) : (
                                <ExpandMore />
                            )}
                        </ListItem>
                        {/* Open public of main nav */}
                        {sharedList.map((item,id) => (
                            <Collapse in={this.state.public_navigationOpen} timeout="auto" unmountOnExit>
                                <List component="div" disablePadding>
                                    <ListItem button
                                              onClick={event => {
                                                  this.handleSubDrawerOpen();
                                                  this.handleFolderData(item.folder_id, item.name);
                                              }}
                                              onDoubleClick={(e) =>
                                                  this.handleSetModal(modalList[3],updateFolder,item.folder_id,item.name)
                                              }
                                    >
                                    {item.permission === 'OWNER' ?
                                        <ListItemIcon>
                                            <Delete onClick={(e)=>this.handleSetModal(modalList[3],deleteFolder,item.folder_id)}/>
                                        </ListItemIcon> 
                                        : null
                                    }                                    
                                        <ListItemText inset primary={item.name} />

                                    </ListItem> 
                                </List>
                            </Collapse>
                        ))}
                    </List>
                    <Divider />


                    <List className={classes.list}>
                        <ListItem
                            button
                            onClick={event => {
                                this.handleDrawerOpen();
                                this.handlePrivateClick();
                            }}
                        >
                            <ListItemIcon>
                                <Folder />
                            </ListItemIcon>
                            <ListItemText primary="private" />
                            {this.state.private_navigationOpen ? (
                                <ExpandLess />
                            ) : (
                                <ExpandMore />
                            )}
                        </ListItem>
                        {/* Open private of nav */}
                        {privateList.map((item, index) => (
                            <Collapse
                                in={this.state.private_navigationOpen}
                                timeout="auto"
                                unmountOnExit
                            >
                                <List component="div" disablePadding>
                                    <ListItem
                                        button
                                        onClick={event => {
                                            this.handleSubDrawerOpen();
                                            this.handleFolderData(item.folder_id,item.name);

                                        }}
                                        onDoubleClick={(e)=>this.handleSetModal(modalList[2],updateFolder,item.folder_id,item.name)}
                                    >
                                     {item.permission === 'OWNER' ?
                                        <ListItemIcon>
                                            <Delete onClick={(e)=>this.handleSetModal(modalList[2],deleteFolder,item.folder_id)}/>
                                        </ListItemIcon> 
                                        : null}
                                        <ListItemText inset primary={item.name} />
                                        <div>{item.count}</div>
                                    </ListItem>
                                </List>
                            </Collapse>
                        ))}
                    </List>
                </Drawer>
                <Drawer
                    variant="permanent"
                    className={classNames(classes.drawer, {
                        [classes.SubDrawerClose]: !this.state.SubOpen
                    })}
                    classes={{
                        paper: classNames( {
                            [classes.SubDrawerOpen]: this.state.SubOpen,
                            [classes.SubDrawerClose]: !this.state.SubOpen
                        }),
                    }}
                    open={this.state.SubOpen}>

                    <div className={classes.toolbar}>
                        <div>                                                            
                            <IconButton>   
                                <NoteAdd color="primary" onClick={(e)=>this.handleSetModal(modalList[4],createNote, this.state.folder_id, '')} />
                            </IconButton>

                            <IconButton>   
                                <Create color="primary" onClick={this.handleModifyFileName} />
                            </IconButton>

                            <IconButton>
                                <Share color="primary" onClick={this.handleNoteExportPdf} />
                            </IconButton>

                            <IconButton>   
                                <Lock color="primary" onClick={this.handleAccessToFile} />
                            </IconButton>

                            <IconButton
                                onClick={this.handleSubDrawerClose}
                                className={classNames(classes.menuButton)}
                            >
                                {theme.direction === "rtl" ? (
                                    <ChevronRight />
                                ) : (
                                    <ChevronLeft />
                                )}
                            </IconButton>
                        </div>
                    </div>
                    <Divider />
                    <div className={classes.drawerOverflow}>
                    <List>
                        {noteList.map(item => (
                            <ListItem button>
                                <ListItemText primary={item.name} 
                                onClick={(e)=>this.handleNoteData(item.id, item.name,item.content)}
                                onDoubleClick={(e)=>this.handleSetModal(modalList[6],updateNote,{note_id:item.id, folder_id: this.state.folder_id},item.name)}/>

                                {/* (array, action, data, text) */}
                                <Delete onClick={(e) => this.handleSetModal(modalList[5], deleteNote, { note_id: item.id, folder_id: this.state.folder_id}, '')} />
                            </ListItem>
                        ))}
                    </List>
                    </div>
                </Drawer>
            </div>
        );
    }
}

Directory.propTypes = {
    classes: PropTypes.object.isRequired,
    theme: PropTypes.object.isRequired
};

export default withStyles(styles, { withTheme: true })(Directory);

0 个答案:

没有答案