要让带有useReducer的React组件在axios调用后重新渲染,可以按照以下步骤操作:
import React, { useState, useReducer, useEffect } from 'react';
// 初始状态
const initialState = {
data: null,
loading: true,
error: null,
};
// reducer函数
const reducer = (state, action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return { ...state, loading: false, data: action.payload, error: null };
case 'FETCH_ERROR':
return { ...state, loading: false, data: null, error: action.payload };
default:
return state;
}
};
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, initialState);
// useEffect监听数据变化
useEffect(() => {
fetchData();
}, []);
// 异步获取数据的函数
const fetchData = async () => {
try {
const response = await axios.get('API_URL');
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', payload: error.message });
}
};
if (state.loading) {
return <div>Loading...</div>;
}
if (state.error) {
return <div>Error: {state.error}</div>;
}
return <div>Data: {state.data}</div>;
};
export default MyComponent;
通过以上步骤,带有useReducer的React组件在axios调用后将能够重新渲染,并根据获取的数据进行相应的展示。
领取专属 10元无门槛券
手把手带您无忧上云