【问题标题】:How to get updated state immediately with redux?如何使用 redux 立即获取更新状态?
【发布时间】:2021-08-30 21:00:01
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以在调度操作后以 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
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2020-08-26
      • 2018-10-28
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2017-05-06
      相关资源
      最近更新 更多