首页 > 解决方案 > 使用 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])

有人可以帮忙吗

标签: reactjsreact-reduxreact-hooks

解决方案


首先发送 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 获取数据。我觉得那应该不错。


推荐阅读