页面有两部分,左侧是 Id 的集合,第二部分是显示数据。
页面第一次加载所有数据(所有Id) ) 被展示。但是用户只能选择 1 个 id,并且可以看到该特定 id 的数据,但获取数据需要时间。因此,在单击 id 和显示数据之间,页面显示了之前的数据(这相当困惑),并且在获取完成后数据突然发生了更改。我想在单击 id 直到出现数据时显示加载页面。
如何做到这一点。在 Id select 上执行下面的函数,然后它会转到 reducer 进行调度操作。
onIdSelection(key, obj) {
if (key && key.id) {
this.props.dispatch(actions.fetchDataActionCreator(key.id));
}
}
在 reducer 中:
export const fetchDataActionCreator = (siteId) => {
return (dispatch) => {
return dispatch({
type: START_FETCH_DEVICES,
payload: api.get({
url: '/api/ndp/v1/collector/telemetry/sites/' + siteId + '/devices',
config: {
apiPrefix: 'none'
}
}).then(payload => dispatch({
type: FINISH_FETCH_DEVICES,
meta: {siteId},
payload})
)
});
};
};
在 reducer 中:
case START_FETCH_DEVICES:
return {...state, dataLoading: true};
case FINISH_FETCH_DEVICES:
return {...state, dataLoading: false, payload: action.payload};
在数据方面:
componentWillReceiveProps(nextProps) {
const {dataUpdated} = nextProps;
if (dataUpdated) {
this.props.dispatch(actions.fetchDataActionCreator(this.props.id));
}
}
这里,当我在 nextProps 中获取数据时 - 整个数据不在所选的 ID 上。
如何仅显示“正在加载”div,直到数据准备好显示。
最佳答案
您应该将 FetchData 操作拆分为 2 个操作:
1. 首先输入:START_FETCH_DEVICES
2. 第二个类型:FINISH_FETCH_DEVICES
要协调调度这两个操作,请使用操作创建器。
例如
export const fetchDataActionCreator = (id) => (dispatch) => {
dispatch ({type: START_FETCH_DEVICES});
api.get({
url: '/api/ndp/v1/id/' + id,
config: {
apiPrefix: 'none'
}
}).then(payload => dispatch({
type: FINISH_FETCH_DEVICES,
meta: {id},
payload})
// I'm not sure that api.get can return Promise, but most async fetch api do so
)
}
现在,您有 fetchDataActionCreator
作为操作创建者,它返回将 dispatch
作为第一个参数的函数。将组件连接到 Redux 时,使用 bindActionCreators
正确包装 fetchDataActionCreator
。
Reducer 应该在状态中设置一些变量来通知应用程序数据正在加载。
例如
function reducer(state, action) {
switch (action.type) {
case START_FETCH_DEVICES:
return {...state, dataLoading: true}
case FINISH_FETCH_DEVICES:
return {...state, dataLoading: false, payload: action.payload}
default:
return state;
}
}
当 state.dataLoading
为 true
时,您的组件可以显示 Loading 消息
关于javascript - 获取数据时显示加载页面 - React Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159887/