我希望在用户点击特定网址时显示加载图片,并在API成功获取数据时隐藏。 我最初没有反应显示图像,我应该添加代码以及如何在API响应成功时隐藏。
这是获取数据的动作创建者。
export const fetchEvents = (requestData) => ({
type: FETCH_EVENTS,
payload: axios.get(requestData.url, fetchEventsConfig)
})
这是用于获取数据的reducer。
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_EVENTS_FULFILLED:
const oldState = Object.assign({}, state)
const response = Object.assign({}, action.payload.data)
const allResults = oldState.results.concat(response.results)
return {
...state,
...response,
results: allResults
}
}
}
我是新手对此做出反应,所以任何帮助都会很棒
答案 0 :(得分:0)
您可以在Redux状态中添加布尔属性以指示加载状态。我们称之为isLoading
。在发送isLoading
时设置FETCH_EVENTS
为真。当您发送FETCH_EVENTS_FULFILLED
时,将其设为false。
使用isLoading
HOF将@connect
的值传递给您的React组件。值为true时呈现加载指示符,如果值为false则呈现内容。
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_EVENTS: {
return {...state, isLoading: true}
}
case FETCH_EVENTS_FULFILLED: {
const response = action.payload.data
const results = [...state.results, ...response.results]
return {
...state,
...response,
results,
isLoading: false
}
}
case FETCH_EVENTS_FAILURE: {
return {...state, isLoading: false}
}
}
}
P.S。
在每个switch/case
限制const
范围内的代码后,在大括号内包含代码。
答案 1 :(得分:0)
写一个加载器文件(loader.js)
import React from 'react'
import {ClipLoader} from "react-spinners";
const Loader = ({ loading, message }) => {
return loading ? (
<div className='wrapper'>
<ClipLoader
size={40}
color={"#123abc"}
loading={loading}
/>
<span className='message'>
{message}
</span>
</div>
) : null
};
export default Loader;
操作中:
export const GET_SERVICE = '[SERVICE REQUEST] GET LIST';
export const GET_SERVICE_SUCCESS = '[SERVICE REQUEST] GET LIST SUCCESS';
export const GET_SERVICE_FAILURE = '[SERVICE REQUEST] GET LIST FAILURE';
export function getService(options) {
const request = axios.post('api/services', {options});
return (dispatch) => {
dispatch({
type: GET_SERVICE
});
try {
request.then((response) =>
dispatch({
type: GET_SERVICE_SUCCESS,
payload: {data: response.data.data, meta: response.data.meta}
})
);
} catch (e) {
dispatch({
type: GET_SERVICE_FAILURE
});
}
}
}
在Reducer中:
const initialState = {
services: [],
loading: false,
hasErrors: false,
};
const serviceReducer = function (state = initialState, action) {
switch (action.type) {
case Actions.GET_SERVICE:
return {...state, loading: true};
case Actions.GET_SERVICE_SUCCESS:
return {
...state,
loading: false,
services: [...action.payload.data],
page: action.payload.meta.page,
total: action.payload.meta.total
};
case Actions.GET_SERVICE_FAILURE:
return {...state, loading: false, hasErrors: true};
default:
return state;
}
};
export default serviceReducer;
在组件中编写以下代码:
<div className="flex flex-1 w-full">
<Loader loading={loading} />
</div>