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

时间:2021-06-15 01:42:34

标签: javascript reactjs redux react-redux redux-thunk

在用户提交表单后,我发送了创建课程功能。

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);
    }
};

1 个答案:

答案 0 :(得分:0)

您可以在分派操作后以 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