使用react redux

时间:2019-01-03 00:32:29

标签: javascript reactjs redux react-redux

我正在学习React-Redux,我陷入了学习的一部分,我试图使用已经存在的形式从表中编辑用户值,从而获取行的值,并传递给表单,并将用户ID保存在变量或某种类型的内容中以更新用户,我不知道如何继续该部分

enter image description here

我的动作: src / actions / user.js

import { ADD_USER, DELETE_USER, UPDATE_USER, FETCH_USER } from '../constants/ActionTypes';
import axios from 'axios';

const apiUrl = 'http://localhost:8080/api/v1';

export const createUser = ({ name, cpfcnpj }) => {
    return (dispatch) => {
        return axios.post(`${apiUrl}/users/`, { name, cpfcnpj })
            .then(response => {
                dispatch(createUserSuccess(response.data.data))
            })
            .catch(error => {
                throw (error);
            });
    };
};

export const createUserSuccess = (data) => {
    return {
        type: ADD_USER,
        payload: {
            _id: data._id,
            name: data.name,
            cpfcnpj: data.cpfcnpj
        }
    }
};

export const deleteUserSuccess = id => {
    return {
        type: DELETE_USER,
        payload: {
            id
        }
    }
}

export const deleteUser = (id) => {
    console.log(id)
    return (dispatch) => {
        return axios.delete(`${apiUrl}/users/${id}`)
            .then(response => {
                dispatch(deleteUserSuccess(id))
            })
            .catch(error => {
                throw (error);
            });
    };
};

export const updateUserSuccess = (data) => {
    return {
        type: UPDATE_USER,
        payload: {
            _id: data._id,
            name: data.name,
            cpfcnpj: data.cpfcnpj
        }
    }
}

export const updateUser = (id, name, cpfcnpj) => {
    console.log(id, name, cpfcnpj)
    return (dispatch) => {
        return axios.put(`${apiUrl}/users/${id}`, { name, cpfcnpj })
            .then(response => {
                dispatch(updateUserSuccess(response.data.data))
            })
            .catch(error => {
                throw (error);
            });
    };
};

export const fetchUsers = (users) => {
    return {
        type: FETCH_USER,
        users
    }
};

export const fetchAllUsers = () => {
    return (dispatch) => {
        return axios.get(`${apiUrl}/users/`)
            .then(response => {
                dispatch(fetchUsers(response.data.data))
            })
            .catch(error => {
                throw (error);
            });
    };
};

我的智能组件CreateUser: src / containers / CreateUser.js

import { connect } from 'react-redux';
import { createUser, updateUser } from '../actions/user';
import NewUser from '../components/NewUser';

const mapDispatchToProps = dispatch => {
    return {
        onAddUser: user => {
            dispatch(createUser(user));
        }
    };
};

export default connect(
    null,
    mapDispatchToProps
)(NewUser);

我的虚拟组件NewUser: src / components / NewUser.js

import React, { Component } from 'react';

class NewUser extends Component {
    state = {
        name: '',
        cpfcnpj: '',
        isEdit: false
    };

    handleInputChange = e => {
        this.setState({
            [e.target.name]: e.target.value
        });
    };

    handleSubmit = e => {
        e.preventDefault();
        if (!this.state.isEdit) {
            if (this.state.name.trim() && this.state.cpfcnpj.trim()) {
                this.props.onAddUser(this.state);
                this.handleReset();
            }
        } else {
            if (this.state.name.trim() && this.state.cpfcnpj.trim()) {
                this.props.onEdit(this.state);
                this.handleReset();
            }
        }

    };

    handleReset = () => {
        this.setState({
            name: '',
            cpfcnpj: ''
        });
    };

    render() {
        return (
            <div>
                <form className="form-inline" onSubmit={this.handleSubmit}>
                    <div className="form-group margin-right">
                        <input
                            type="text"
                            placeholder="Name"
                            className="form-control"
                            name="name"
                            onChange={this.handleInputChange}
                            value={this.state.name}
                        />
                    </div>
                    <div className="form-group margin-right">
                        <input
                            type="text"
                            placeholder="CPF/CNPJ"
                            className="form-control"
                            name="cpfcnpj"
                            onChange={this.handleInputChange}
                            value={this.state.cpfcnpj}>
                        </input>
                    </div>
                    <div className="form-group">
                        <button type="submit" className={this.state.isEdit ? "btn btn-success margin-right hidden" : "btn btn-success margin-right"}>
                            <span className="glyphicon glyphicon-plus" aria-hidden="true"></span>
                            &nbsp;
                            Adicionar
                        </button>
                        <button type="submit" className={this.state.isEdit ? "btn btn-primary margin-right" : "btn btn-primary margin-right hidden"}>
                            <span className="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
                            &nbsp;
                            Salvar
                        </button>
                        <button type="button" className="btn btn-default margin-right" onClick={this.handleReset}>
                            <span className="glyphicon glyphicon-erase" aria-hidden="true"></span>
                            &nbsp;
                            Limpar
                        </button>
                    </div>
                </form>
            </div>
        );
    }
}

export default NewUser;

src / containers / UserList.js

import React from 'react';
import { connect } from 'react-redux';
import User from '../components/User';
import { deleteUser, updateUser } from '../actions/user';

function UserList({ users, onDelete, onEdit }) {
    if (!users.length) {
        return (
            <div className="margin-top">
                No Users
            </div>
        )
    }
    return (
        <div className="margin-top">
            <table className="table table-striped">
                <thead>
                    <tr>
                        <th scope="col">Nome</th>
                        <th scope="col">CPF/CNPJ</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => {
                        return (
                            <User user={user} onDelete={onDelete} key={user._id} onEdit={onEdit} />
                        );
                    })}
                </tbody>
            </table>
        </div>
    );
}

const mapStateToProps = state => {
    return {
        users: state.users
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onDelete: id => {
            dispatch(deleteUser(id));
        },
        onEdit: id => {
            dispatch(updateUser(id))
        }
    };
};

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

src / reducers / userReducer.js

import { ADD_USER, DELETE_USER, UPDATE_USER, FETCH_USER } from '../constants/ActionTypes';

export default function userReducer(state = [], action) {
    switch (action.type) {
        case ADD_USER:
            return [...state, action.payload];
        case DELETE_USER:
            return state.filter(user => user._id !== action.payload.id);
        case UPDATE_USER:
            return [...state, action.payload];
        case FETCH_USER:
            return action.users;
        default:
            return state;
    }
}

我认为但无法复制的解决方案

我需要获取作为值在UserList中的键的值表项的id的值,传递给用户组件按钮的onClick参数,并在单击某个表中的edit时传递id的值项,以便能够使用NewUser中的onEdit编辑表格项。


卡在解决方案ma_dev_15

我用当前用户创建了一个const initialState,但是我的userReducer状态只是看起来用户,

src / recuders / userReducer.js     从'../constants/ActionTypes'导入{ADD_USER,DELETE_USER,UPDATE_USER,UPDATE_CURRENT_USER,FETCH_USER};

const initialState = {
    users: [],
    currentUser: {},
}

export default function userReducer(state = initialState, action) {
    switch (action.type) {
        case ADD_USER:
            return [...state, action.payload];
        case DELETE_USER:
            return state.filter(user => user._id !== action.payload.id);
        case UPDATE_USER:
            return updateObject(state, action)
        case UPDATE_CURRENT_USER:
            return [...state, action.currentUser];
        case FETCH_USER:
            return action.users;
        default: 
            return state;
    }
}

function updateObject(array, action) {

    return array.map((item, index) => {
        if (item._id !== action.payload._id) {
            return item
        }

        return {
            ...item,
            ...action.payload
        }
    })
}

出口减速机 src / reducers / index.js

import { combineReducers } from 'redux';
import users from './userReducer';
import currentUser from './userReducer';

export default combineReducers({
    users: users,
    currentUser: currentUser
});

用户操作:src / actions / user.js

//Ommited
export const updateCurrentUserSuccess = (currentUser) => {
    return {
        type: UPDATE_CURRENT_USER,
        currentUser
    }
}

export const updateCurrentUser = (id) => {
    return (dispatch) => {
        return axios.get(`${apiUrl}/users/${id}`)
            .then(response => {
                dispatch(updateCurrentUserSuccess(response.data.data))
            })
            .catch(error => {
                throw (error);
            });
    };
};
//Ommited

我将UserList连接到CreateUser

src / components / containers / UserList

import React from 'react';
import { connect } from 'react-redux';
import User from '../components/User';
import { deleteUser, updateCurrentUser } from '../actions/user';
import NewUser from '../components/NewUser';

function UserList({ users, onDelete, onEditUser }) {
    if (!users.length) {
        return (
            <div className="margin-top">
                No Users
            </div>
        )
    }
    return (
        <div className="margin-top">
            <table className="table table-striped">
                <thead>
                    <tr>
                        <th scope="col">Nome</th>
                        <th scope="col">CPF/CNPJ</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => {
                        return (
                            <User user={user} onDelete={onDelete} onEditUser={onEditUser} key={user._id} />
                        );
                    })}
                </tbody>
            </table>
        </div>
    );
}

const mapStateToProps = state => {
    return {
        users: state.users
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onDelete: id => {
            dispatch(deleteUser(id));
        },
        onEditUser: (id) => {
            dispatch(updateCurrentUser(id))
        }
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(UserList, NewUser);

当我单击“编辑”并尝试在NewUser.js中查看console.log(Store.getState)时,我只是返回了所有用户,而我没有currentUser。

1 个答案:

答案 0 :(得分:1)

您可以这样创建userReducer状态:

const initialState = {
  users: [],
  currentUser :{},
}

export default function userReducer(state = initialState, action) {
    switch (action.type) {
        case ADD_USER:
            return [...state, action.payload];
        case DELETE_USER:
            return state.filter(user => user._id !== action.payload.id);
        case UPDATE_USER:
            return [...state, action.payload];
        case FETCH_USER:
            return action.users;
        default:
            return state;
    }
}

在那之后,让我告诉您一些简单的步骤:

  1. 单击“编辑”按钮时,通过userId并进行相应的操作更新 currentUser中的userReducer
  2. 使NewUser组件成为连接组件,并从存储中获取currentUser并将其设置为输入字段。
  3. 成功编辑后,将currentUser更新为空并更新users列表

我希望你明白我的意思。让我知道你是否卡在某个地方。