如何使用redux立即获得更新状态



在用户提交表单后,我调度了create course函数。

const handleCreateCourse = () => {
dispatch(createCourse(courseData));
// ??
};

我怎样才能获得和使用"_id";新创建的课程将立即来自后端,并将以更新状态保存?这样我就可以做以下事情:

const courses = useSelector(state => state.courses);
const handleCreateCourse = () => {
dispatch(createCourse(courseData));
// ??
const newCourse = courses[courses.length-1];
history.push(`/course/${newCourse._id}`);
};

createCourse函数使用redux thunk,如下所示:

export const createCourse = (course) => async (dispatch) => {
try {
const { data } = await api.createCourse(course);
dispatch({ type: CREATE_COURSE, payload: data });
} catch (error) {
console.log(error);
}
};

您可以在调度操作后在thunk中返回API响应。

例如

import { createStore, applyMiddleware, combineReducers } from 'redux';
import ReduxThunk from 'redux-thunk';
const thunk = ReduxThunk.default;
const api = {
async createCourse(name) {
return { data: { _id: '100', name } };
},
};
function coursesReducer(state = [], action) {
return state;
}
const rootReducer = combineReducers({
courses: coursesReducer,
});
const store = createStore(rootReducer, applyMiddleware(thunk));
const CREATE_COURSE = 'CREATE_COURSE';
export const createCourse = (course) => async (dispatch) => {
try {
const { data } = await api.createCourse(course);
dispatch({ type: CREATE_COURSE, payload: data });
return data;
} catch (error) {
console.log(error);
}
};
const handleCreateCourse = () => {
store.dispatch(createCourse({ name: 'math' })).then((newCourse) => {
console.log('newCourse: ', newCourse);
console.log(`/course/${newCourse._id}`);
});
};
handleCreateCourse();

实验结果:

newCourse:  { _id: '100', name: { name: 'math' } }
/course/100

相关内容

  • 没有找到相关文章

最新更新