使用useSelector更新对象



我是react hook的新手,我正试图通过它的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])

有人能帮助吗

hi您可以使用useDisaptch

const dispatch = useDispatch()
const getOneEmployee = useCallback(
(id) => dispatch(getSingleEmployee(Id)),
[dispatch]
)
useEfffect(()=>{  
if (emp != null) {
setFull_name(emp.full_name)
setEmail(emp.email)
setPhone_number(emp.phone_number)
setAddress(emp.address)
}
getOneEmployee(empById
},[emp,empById])

首先只发送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

还要确保在组合的reducer中添加reducer,以便使用useSelector获取数据。我认为那应该很好。

相关内容

  • 没有找到相关文章

最新更新