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

How to get updated state immediately with redux?

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

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

您可以在发送操作后 return 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