【发布时间】:2018-09-19 10:02:01
【问题描述】:
我正在尝试学习 React / Redux 并使用 .Net core Api 作为后端服务来构建简单的应用程序。
我的要求
当用户点击保存按钮时添加项目
重定向到List页面,再次加载数据,检索新添加的数据
我必须重新加载数据,不能只在列表中追加新项目,因为我需要获取刚刚生成的新添加项目的 keyId
所以,我在我的操作文件中链接承诺,以便在 AddItem 成功后调用 LoadItems。
如果我不链接这些承诺,我将无法在列表页面中看到新创建的项目。重定向到 '/todo' 发生得如此之快,甚至在之前 AddItem() 尚未完成。如果我为重定向添加 2 秒延迟,我可以看到新项目。
操作
export const addTodoItemSuccess = todoItem => ({ type: actionTypes.ADD_TODO_ITEM_SUCCESS, payload: todoItem });
export const loadTodoItemsSuccess = items => ({ type: actionTypes.LOAD_TODO_SUCCESS, payload: items });
export const loadTodoItems = () => {
return function (dispatch) {
return TodoService.getAll().then(items => {
dispatch(loadTodoItemsSuccess(items));
});
};
}
export const addTodoItem = (item) => {
return function (dispatch) {
return TodoService.add(item).then(() => {
return TodoService.getAll().then(items => {
dispatch(loadTodoItemsSuccess(items));
});
});
};
}
减速器
import * as actionTypes from '../actions/actionTypes';
const todoReducer = (state = [], action) => {
switch (action.type) {
case actionTypes.LOAD_TODO_SUCCESS:
return action.payload;
default:
return state;
}
}
export default todoReducer;
AddTodoPage 容器
submitNewTodo = event => {
event.preventDefault();
this.props.addTodoItem(this.state.item);
//redirect to Todo List Page after saving
this.context.router.history.push(`/todo`);
}
TodoListPage 容器
componentDidMount = () => {
this.props.dispatch(loadTodoItems());
}
它按预期工作,我可以在列表中看到新项目。但问题是它正在向 Api 发送 TWO GetAll() 查询。
第一个调用来自 Actions.js,第二个调用来自 TodoListPage.js 中的componentDidMount。
如果我从
componentDidMount中删除了loadTodoItems(),当我导航到 TodoListPage '/todo' 时,我无法查看任何项目,因为这些项目尚未加载。
在教程中,他们通常在index.js 中执行store.dispatch(loadTodoItems()); 以使其可用。即使在用户尚未导航到该页面(查找数据除外)之前,我也觉得加载数据是错误的。
您能否建议我实现上述要求的最佳方法是什么?我不想调用 Api 两次来刷新数据。
完整的代码集可以在这里找到:https://github.com/ttcg/react-redux-todo/tree/todocrud/src
【问题讨论】:
标签: reactjs react-redux