1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| function AppHooks() { const initialState = { data: null, error: null, loaded: false, fetching: false, } const [data,setData] = useState(); ... const reducer = (state, newState) => ({ ...state, ...newState }) const [state, setState] = useReducer(reducer, initialState);
async function fetchData() { const response = await fetch(API_URL); const { data, status } = { data: await response.json(), status: response.status }
if (status !== 200) { return setState({ data, error: true, loaded: true, fetching: false, }) }
setState({ data, error: null, loaded: true, fetching: false, }) }
useEffect(() => { fetchData() }, [])
const { error, data } = state return error ? <div> Sorry, 网络异常 :( </div> : <pre>{JSON.stringify(data, null, ' ')}</pre> }
|