Reactjs 胡克斯与雷杜传奇

Reactjs 胡克斯与雷杜传奇,reactjs,redux,react-hooks,Reactjs,Redux,React Hooks,我正在学习redux挂钩,并想知道如何将其与redux传奇一起使用 目前用saga编写的代码如下 export const getCenters = () => ({ type: types.CENTERS_REQUEST, }); import { DEFAULT_ERROR_MSG } from '../../constants'; import { instance as centerProvider } from '../services/centerProvider';

我正在学习redux挂钩,并想知道如何将其与redux传奇一起使用

目前用saga编写的代码如下

export const getCenters = () => ({
  type: types.CENTERS_REQUEST,
});
import { DEFAULT_ERROR_MSG } from '../../constants';
import { instance as centerProvider } from '../services/centerProvider';

function* fetchCenters() {
  try {
    const response = yield call(centerProvider.getCenters);
    const centers = response.data.data.centers;

    // dispatch a success action to the store
    yield put({ type: types.CENTERS_SUCCESS, centers});

  } catch (error) {
    // dispatch a failure action to the store with the error
    yield put(DEFAULT_ERROR_MSG);
  }
}

export function* watchCenterRequest() {
  yield takeLatest(types.CENTERS_REQUEST, fetchCenters);
}

export default function* centerSaga() {
  yield all([
    watchCenterRequest()
  ]);
}
centers.js

saga文件的定义如下

export const getCenters = () => ({
  type: types.CENTERS_REQUEST,
});
import { DEFAULT_ERROR_MSG } from '../../constants';
import { instance as centerProvider } from '../services/centerProvider';

function* fetchCenters() {
  try {
    const response = yield call(centerProvider.getCenters);
    const centers = response.data.data.centers;

    // dispatch a success action to the store
    yield put({ type: types.CENTERS_SUCCESS, centers});

  } catch (error) {
    // dispatch a failure action to the store with the error
    yield put(DEFAULT_ERROR_MSG);
  }
}

export function* watchCenterRequest() {
  yield takeLatest(types.CENTERS_REQUEST, fetchCenters);
}

export default function* centerSaga() {
  yield all([
    watchCenterRequest()
  ]);
}
所以问题是,

  • 如果我们使用钩子,我们还需要redux吗
  • 我们如何使用钩子重写上面的代码
  • “如果我们使用钩子,还需要redux吗?”
  • 如果需要,可以使用
    useReducer
    hook代替redux。但是,如果在DOM树的不同分支中深度嵌套的不同组件之间有一个共享状态,那么使用
    useReducer
    实现可能有点复杂。因此,使用redux和saga与hook并不矛盾。如果喜欢功能组件而不是类组件,则只需要挂钩

  • “我们如何使用钩子重写上述代码?”
  • 您可以重新制作类组件
    中心
    ,以实现如下功能组件:

    function Centers(props) {
        useEffect(() => {
            props.getCenters();
        }, []);
    
        return (
            //render what you need here
        );
    }