在Reducer React Typescript中设置条件有效负载,可以通过以下步骤实现:
interface AppState {
isLoading: boolean;
data: any;
error: string | null;
}
const initialState: AppState = {
isLoading: false,
data: null,
error: null,
};
enum ActionTypes {
FETCH_DATA_REQUEST = "FETCH_DATA_REQUEST",
FETCH_DATA_SUCCESS = "FETCH_DATA_SUCCESS",
FETCH_DATA_FAILURE = "FETCH_DATA_FAILURE",
}
interface FetchDataRequestAction {
type: ActionTypes.FETCH_DATA_REQUEST;
}
interface FetchDataSuccessAction {
type: ActionTypes.FETCH_DATA_SUCCESS;
payload: any;
}
interface FetchDataFailureAction {
type: ActionTypes.FETCH_DATA_FAILURE;
payload: string;
}
type Action = FetchDataRequestAction | FetchDataSuccessAction | FetchDataFailureAction;
const reducer = (state: AppState, action: Action): AppState => {
switch (action.type) {
case ActionTypes.FETCH_DATA_REQUEST:
return {
...state,
isLoading: true,
error: null,
};
case ActionTypes.FETCH_DATA_SUCCESS:
return {
...state,
isLoading: false,
data: action.payload,
};
case ActionTypes.FETCH_DATA_FAILURE:
return {
...state,
isLoading: false,
error: action.payload,
};
default:
return state;
}
};
const MyComponent: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchData = async () => {
dispatch({ type: ActionTypes.FETCH_DATA_REQUEST });
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
dispatch({ type: ActionTypes.FETCH_DATA_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: ActionTypes.FETCH_DATA_FAILURE, payload: error.message });
}
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
{state.isLoading ? (
<p>Loading...</p>
) : state.error ? (
<p>Error: {state.error}</p>
) : (
<p>Data: {JSON.stringify(state.data)}</p>
)}
</div>
);
};
在上述代码中,我们定义了三种操作类型:FETCH_DATA_REQUEST、FETCH_DATA_SUCCESS和FETCH_DATA_FAILURE。当调用fetchData函数时,首先发送FETCH_DATA_REQUEST操作,然后根据请求结果分别发送FETCH_DATA_SUCCESS或FETCH_DATA_FAILURE操作。Reducer函数根据操作类型更新状态,组件根据状态渲染不同的UI。
这是一个简单的示例,你可以根据实际需求扩展Reducer函数和操作类型。在实际开发中,你可能需要处理更多的状态和操作类型,并且根据具体场景进行逻辑处理。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云