首页 > 解决方案 > 如何在 redux reducer 中更新我的初始状态

问题描述

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

当我单击 isAddUser 按钮时,如何从我的减速器更改状态 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 从初始状态更新为 true

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;
    }
}

标签: reactjsreduxreact-reduxreducers

解决方案


创建名为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
}

推荐阅读