Hooks 和 Redux Saga

Hooks and Redux Saga

我正在学习 redux hooks 并想知道如何将它与 redux saga 一起使用。

目前用saga编写的代码如下

centers.js

componentDidMount() {
    this.props.getCenters();
  }

...

<tbody>
                            {
                              this.props.centers ?
                                <React.Fragment>
                                  {
                                    centers.map((center, index) =>
                                      <tr key={index}>
                                        <td>{center.name}</td>
                                        <td>{center.zip}</td>
                                      </tr>
                                    )
                                  }
                                </React.Fragment>
                              :
                                <tr>
                                  <td> No data available</td>
                                </tr>

                            }
                          </tbody>

动作文件定义如下。

export const getCenters = () => ({
  type: types.CENTERS_REQUEST,
});

saga文件定义如下。

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

所以问题是,

  1. "Do we still need redux if we use hooks?"

如果你愿意,你可以使用 useReducer hook 而不是 redux。但是,如果您在 DOM 树的不同分支中深度嵌套的不同组件之间有共享状态,则 useReducer 的实现可能会有点复杂。所以使用redux和saga与hooks并不矛盾。如果比 class 组件更喜欢功能组件,则只需要挂钩。

  1. "How can we rewrite the above code using hooks?"

您可以重新制作您的 class 组件 Centers 以像这样运行组件:

function Centers(props) {
    useEffect(() => {
        props.getCenters();
    }, []);

    return (
        //render what you need here
    );
}