reactjs - 使用 useSelector 更新对象
问题描述
我是反应钩子的新手,我正在尝试通过它的 ID 更新和获取 Employee,所以在 redux 中我得到了它,但它没有显示在屏幕上,意味着组件中的含义。这是我的代码
const EditEmployee = ({history, match}) => {
const empById = match.params.id
const dispatch = useDispatch()
const employee = useSelector((state) => state.employee.employee)
const {loading, emp} = employee
const [full_name, setFull_name] = useState('');
const [email, setEmail] = useState('');
const [phone_number, setPhone_number] = useState('');
const [address, setAddress] = useState('');
useEffect(() => {
if (emp != null) {
setFull_name(emp.full_name)
setEmail(emp.email)
setPhone_number(emp.phone_number)
setAddress(emp.address)
}
dispatch(getSingleEmployee(empById))
}, [emp, empById, dispatch])
有人可以帮忙吗
解决方案
首先发送 getEmployee 动作
useEffect(() => {
dispatch(getSingleEmployee(empById))
}, [dispatch, empById])
然后如果 emp 数据更新,则更新剩余字段
useEffect(() => {
if (employee!= null) {
setFull_name(employee.full_name)
setEmail(employee.email)
setPhone_number(employee.phone_number)
setAddress(employee.address)
}
}, [employee])
如果这是您的初始状态
const initialState = {
employees: [],
employee: {},
loading: false
}
那么 useSelector 应该是
const employee = useSelector((state) => state.employee) // reducer name - employee
const {loading, employee} = employee
还要确保在组合减速器中添加减速器以使用 useSelector 获取数据。我觉得那应该不错。
推荐阅读
- batch-file - 批处理 - 功能 - 参数不起作用
- android - 在我的应用中显示受保护的版权视频
- html - 默认隐藏RPubs文档中的工具栏
- github - 在应用程序 GUI 上注释 github 问题
- c++ - 在 C++ 中初始化邻接矩阵
- c++ - “打开文件”对话检测
- maven - 无法访问子 pom 文件中的父库文件夹?
- c# - 并行执行查询会导致更多时间 [SQL Server]
- ejabberd - org.apache.xmlrpc.XmlRpcException: 错误 -118 {error,access_rules_unauthorized}
- c# - 寻找针对多种可连接条件的设计模式建议