如何以最高优先级运行我的useEffect,使我的状态可以先被更新,然后再做进一步的处理。
我想让我的axios部分先在useEffect里面运行,这样我的状态就可以先更新,然后再进一步使用。
这里有一个错误。TypeError: Cannot read property 'id' of undefined
当我的控制台显示状态没有被更新,它持有空数组。
这是我的代码。
const initialState = {
staff: [],
isFetching: false,
hasError: false
}
const Staff = ({ setStaffid }) => {
const [states, dispatch] = useReducer(reducer, initialState)
console.log(states)
useEffect(() => {
dispatch({
axios.get("https://example.com/staff")
.then(response => {
console.log(response)
console.log(response.data)
dispatch({
type: "FETCHSUCCESS",
payload: response.data.access
});
})
.catch(error => {
console.log(error);
dispatch({
type: "FETCHFAILURE"
});
});
}, );
useEffect(() => {
const id = states.staff[0].id;
setStaffid(id);
}, []);
return (
<div>
</div>
);
};
export default Staff;
错误的原因是你正在尝试访问属性 "id "在一个 undefined
对象。
改变 useEffect
useEffect(() => {
const staff = states.staff[0];
if(staff) setStaffid(staff.id);
}, [states.staff]);
要摆脱错误,只需改变你的初始状态。
const initialState = {
staff: [{}],
isFetching: false,
hasError: false
}
希望对你有帮助。