【发布时间】:2019-04-02 21:31:04
【问题描述】:
我的 redux thunk 实现导致覆盖数组数据。
显然流程中有问题,但我无法弄清楚。
基本上我有两个组件 StringInstrument 和 UsersListedItems。
StringInstrument 将从数据库(通过 axios)获取数据以获取项目所有者列表。
将为每个所有者创建一个 UsersListedItems 组件,该组件还将通过所有者 ID 从数据库(图像)中获取数据。
所以我会说 StringInstrument 实际上创建了 UsersListedItems。
这是 StringInstrument 的一些代码:
if (this.props.error) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <CircularProgress/>;
}
return (
<div>
<Grid container spacing={24}>
{this.props.itemOwner.map((item, index) => (
<Grid item xs={6} sm={3} key={index}>
<UsersListedItems
ownerId={item.ownerId}
userName={item.userName}
categoryId={1}>
</UsersListedItems>
</Grid >)
)}
</Grid>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
itemOwner: state.itemOwner.data,
isLoading: state.itemOwner.isLoading,
error: state.itemOwner.error
}
}
const mapDispatchToProps = (dispatch) => {
return {
getItemOwners: (id) => dispatch(itemAction.getItemOwners(id))
}
这就是我实现 action 和 reducer 的方式。
export function getItemOwner(state = initState, action) {
switch (action.type) {
case GET_ITEM_OWNER_START:
state = Object.assign({}, state, { isLoading: true });
break;
case GET_ITEM_OWNER_SUCCESS:
state = Object.assign({}, state, { data: action.payload, isLoading: false });
break;
case GET_ITEM_OWNER_ERROR:
state = Object.assign({}, state, { error: action.payload, isLoading: false });
break;
}
return state;
}
export function getItems(state = initState, action) {
switch (action.type) {
case GET_ITEMS_START:
state = Object.assign({}, state, { isLoading: true });
break;
case GET_ITEMS_SUCCESS:
state = Object.assign({}, state, { data: action.payload, isLoading: false });
break;
case GET_ITEMS_ERROR:
state = Object.assign({}, state, { error: action.payload, isLoading: false });
break;
}
return state;
export const getItemOwners = (categoryId) => {
return (dispatch, getState) => {
//make async call to database
dispatch({ type: GET_ITEM_OWNER_START });
axios.get('api/items/owner/category/' + categoryId)
.then(function (response) {
dispatch({ type: GET_ITEM_OWNER_SUCCESS, payload: response.data });
})
.catch(function (error) {
dispatch({ type: GET_ITEM_OWNER_ERROR, payload: error });
});
}
};
export const getItems = (categoryId, ownerId) => {
return (dispatch, getState) => {
dispatch({ type: GET_ITEMS_START });
axios.get('api/items/' + categoryId + '/' + ownerId)
.then(function (response) {
dispatch({ type: GET_ITEMS_SUCCESS, payload: response.data });
})
.catch(function (error) {
dispatch({ type: GET_ITEMS_ERROR, payload: error });
});
}
我不确定如何管理\控制调度程序的流程,以便它适合组件结构而不覆盖收集的数据。
正如您在附加图片中看到的那样,4 个“GET_ITEM_SUCCESS”位于末尾,每个都将覆盖下一个。
希望我清楚并为这个长代码示例道歉。
谢谢
【问题讨论】:
标签: reactjs redux redux-thunk