【发布时间】:2020-03-09 08:37:43
【问题描述】:
我正在尝试以表单的形式加载从 API 获得的一些数据,但我的状态挂钩似乎有问题。
在下面的代码中,我使用挂钩来定义员工和员工 ID。
之后,我尝试使用 useEffect 来模仿类组件中的 componentDidMount 函数。
在这里,我检查 url 中是否有参数,并使用setEmployeeId(props.match.params.employeeId) 更新employeeId 状态。
问题是,我的状态值没有更新,我的整个流程崩溃了。
请记住,我宁愿为此使用函数组件。
export default function EmployeeDetail(props) {
const [employeeId, setEmployeeId] = useState<number>(-1);
const [isLoading, setIsLoading] = useState(false);
const [employee, setEmployee] = useState<IEmployee>();
useEffect(() => componentDidMount(), []);
const componentDidMount = () => {
// --> I get the correct id from the params
if (props.match.params && props.match.params.employeeId) {
setEmployeeId(props.match.params.employeeId)
}
// This remains -1, while it should be the params.employeeId
if (employeeId) {
getEmployee();
}
}
const getEmployee = () => {
setIsLoading(true);
EmployeeService.getEmployee(employeeId) // --> This will return an invalid employee
.then((response) => setEmployee(response.data))
.catch((err: any) => console.log(err))
.finally(() => setIsLoading(false))
}
return (
<div>
...
</div>
)
}
【问题讨论】:
-
setEmployeeId的新值可能在下一次渲染中可用。您正在运行的代码是同一渲染的一部分,因此尚未设置该值。因为你在同一个函数中,所以使用你已经拥有的值props.match.params.employeeId。请记住,当您调用set*时,您是在指示 React 将更新排队。更新可能会在 React 决定时发生。
标签: reactjs react-functional-component