如何以最高优先级运行useEffect,以便可以首先更新我的状态,然后可以进行进一步处理
我希望我的axios部分应该首先在useEffect内部运行,以便可以首先更新我的状态,然后再使用它。
这是错误:TypeError: Cannot read property 'id' of undefined
当我控制台显示状态未更新时,它持有空数组
这是我的代码:
import React, {useEffect, useReducer } from 'react';
import { Tab, Nav } from 'react-bootstrap';
import axios from "axios";
const initialState = {
staff: [],
isFetching: false,
hasError: false
}
const reducer = (state, action) => {
switch (action.type) {
case "FETCHREQUEST":
return {
...state,
isFetching: true,
hasError: false
};
case "FETCHSUCCESS":
return {
...state,
staff: action.payload,
};
case "FETCHFAILURE":
return {
hasError: true,
isFetching: false
};
default:
return state;
}
}
const FetchingStaff = ({ setStaffid }) => {
const [states, dispatch] = useReducer(reducer, initialState)
console.log(states)
useEffect(() => {
dispatch({
type: "FETCHREQUEST"
});
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"
});
});
}, );
// For initial value
useEffect(() => {
const id = states.staff[0].id;
setStaffid(id);
}, []);
return (
<div>
<Tab.Container
defaultActiveKey={states.staff[0].id}
onSelect={id => setStaffid(id)}
>
<Nav variant="pills" className="flex-column">
{states.staff.map(staff => (
<Nav.Item key={staff.id}>
<Nav.Link eventKey={staff.id}>{staff.name}</Nav.Link>
</Nav.Item>
))}
</Nav>
</Tab.Container>
</div>
);
};
export default FetchingStaff;
错误是因为您试图访问undefined
对象的属性“ id” 。
更改 useEffect
useEffect(() => {
const staff = states.staff[0];
if(staff) setStaffid(staff.id);
}, [states.staff]);
要摆脱错误,只需更改您的initialState。
const initialState = {
staff: [{}],
isFetching: false,
hasError: false
}
希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句