如何在Redux Reducer中更新我的初始状态

时间:2018-08-28 11:11:43

标签: reactjs redux react-redux reducers

嗨,我有这个用户列表容器,它也呈现用户表单容器。 我只是将这两个容器都放在了如果在初始页面加载中将显示用户列表的情况下。 单击添加用户按钮后,将显示用户表单。

当我单击isAddUser按钮时,如何从我的reducer中更改isAddUser的状态??

addUser(){
    //button to show add user form 
    //update the reducers initial state isAddUser
}

if(this.props.isAddUser){
    return (
        <div className="row">
            <div className="container table-responsive">
                <UserForm/>
            </div>
        </div>
    )
} else {
    return(
             <div className="row">
                <div className="container table-responsive">
                    <div className="text-right"> 
                        <button 
                            className="btn btn-primary text-right"
                            onClick={this.addUser.bind(this)}>
                            Add User
                        </button>
                    </div>
                    <table className="mt-1 table table-hover">
                        <thead className="thead-light">
                            <tr>
                                <th>Name</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th></th>
                            </tr>
                        </thead>                
                        {userList}  
                    </table>
                </div>    
            </div> 
          )
      }
}


const mapStateToProps = state => ({
    users: state.users.items,
    isAddUser: state.users.isAddUser
})

export default connect(mapStateToProps, { fetchUsers, deleteUser })(UserList);

减速器

我需要将isAddUser从初始状态更新为false

import { FETCH_USERS, DELETE_USER } from '../actions/User/Types';

const initialState = {
   items: [],
   item: {},
   isAddUser: false
}
export default function(state = initialState, action){
    switch(action.type){
        case FETCH_USERS:
          //code here

        case DELETE_USER:
          //code here

        default: 
           return state;
    }
}

1 个答案:

答案 0 :(得分:0)

创建名为UPDATE_ADD_USER的新操作。 当您调用此操作更新变量时。

case UPDATE_ADD_USER:
        return {...state, isAddUser: true};

创建类似fetchUsers, deleteUser的动作,然后将其发送到动作列表中。

export default connect(mapStateToProps, { fetchUsers, deleteUser,updateAddUser })(UserList);

addUser函数中

addUser(){
   this.props.updateAddUser();//call new action created
}
相关问题