reactjs - 如何在 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;
}
}
解决方案
创建名为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
}
推荐阅读
- java - Java读取文件:列出无效数据
- dart - 如何将某人的用户 ID 存储在我的朋友集合中以及如何使用带有颤振的 Firestore 检索该用户的数据?
- python-3.x - Python - 成功安装后找不到模块
- php - openssl_pkey_new 返回空白且没有错误消息
- html - 获取按钮以将当前用户的 id 添加到字段
- reactjs - 需要关于 nextjs 动态 url 的帮助
- apache2 - 设置 apache 反向代理从 localhost 到 domain.com/etherpad
- spring-kafka - Spring Kafka Streams:缺少类型信息
- python - 在张量流中组合多图的最佳方法是什么?
- r - 带有变换和颜色映射的 plot_ly