处理从API中加载和null案例在react/redux
问题描述:
试图显示一个加载器一点,然后显示结果 - 混淆如何显示空结果方案如果我用零结果加载加载器? 这里是我的动作和减速机: - 我想显示在每一个获取调用之前我得到的数据.. 行动装载机:处理从API中加载和null案例在react/redux
export function fetchdata(keyWord) {
return function(dispatch) {
Request.get(endpoint).then((response) => {
dispatch({
type: FETCHING,
});
dispatch({
type: API_FETCH,
payload: response.data,
});
}).catch((error) => {
dispatch({
type: API_FAILURE,
payload: error,
});
});
};
}
减速机:
const initialState = {
count: 0,
};
export default function myReducer(state = initialState, action) {
switch (action.type) {
case FETCHING:
return {
...state,
data: action.payload,
count: count += 1,
};
case API_FETCH:
return {
...state,
data: action.payload,
count: state.count > 0 ? state.count -= 1 : 0,
};
case API_FAILURE:
return {
...state,
count: state.count > 0 ? state.count -= 1 : 0,
data: action.payload,
};
default:
return state;
}
}
父组件:
....
fetchData(value) {
this.setState({ isLoading: true }); - setting true/passing to child
this.props.fetchdata(value);
}
return (
<Child isLoading={this.state.isLoading} data={this.props.data} />
儿童:
render() {
if (this.props.isLoading && !this.props.data) return (<Loader />);
const data = this.props.data ? this.props.data : [];
const results = data.map((item, index) => {
return (
<div key={index}>
<div>{item.name}</div>
</div>);
});
return (
<div className={`data ${visible}`}>
<div className="data__list">
{data}
</div>
</div>
);
}
答
我回答了一个问题,可能会有所帮助。 Same logic with here please look my answer
如果你是多次提取。那么不要使用布尔值使用计数器。
上减速LOAD_DATA_REQUEST增加fecthing_count
在LOAD_DATA_ERROR或LOAD_DATA_SUCCESS减少fetching_count
如果fetching_count是0,这意味着你不取,并准备渲染
照你的意见认为我们命名API ActionTypes (检查我的旧回答,了解我的意思与行动类型)为用户USER_API_REQUEST,USER_API_ERROR,USER_API_SUCCESS为其他人使用相同的模式* _API_REQUEST,* _API_ERROR,* _API_SUCCESS
你的减速器:
if (action.type.endsWith('API_REQUEST'))
{
//maybe you load
newState.fetching= newState.fetching++; // increased then it is fetching
return newState;
}
if (action.type.endsWith('API_SUCCESS'))
{
const res = action.payload;
newState.fetching= newState.fetching >0 ? newState.fetching-- : 0 ; // decreased or setted as 0 .. if 0 then no fetching
return newState;
}
if (action.type.endsWith('API_ERROR'))
{
//u can show error message
newState.fetching= newState.fetching >0 ? newState.fetching-- : 0 ; // decreased or setted as 0 .. if 0 then no fetcing
return newState;
}
并在你的组件上访问你的reducer并检查属性获取。
如果获取属性大于0,那么你已经获取请求(加载)其他可以使您的项目
错误是你的终极版功能在你的终极版功能
export function fetchdata(keyWord) {
return function(dispatch) {
/// you have to do it before starting request
dispatch({
type: FETCHING,
});
Request.get(endpoint).then((response) => {
/// Request is Success because of this it is not rising
/*
dispatch({
type: FETCHING,
});
*/
dispatch({
type: API_FETCH,
payload: response.data,
});
}).catch((error) => {
dispatch({
type: API_FAILURE,
payload: error,
});
});
};
}
有你有任何减速? – Aaqib
是的,我确实拥有它 - 试图在实际调度之前用bool调度提取isFetching:true - 但我不工作,也不知道如何重置它 - – monkeyjs