设置React useReducer的最佳方法

时间:2018-11-05 05:45:43

标签: javascript reactjs react-hooks

我设置了reducer.js文件以使用React的useReducer

https://reactjs.org/docs/hooks-reference.html#usereducer

import {useReducer} from 'react';

const initialState = {
  test: 0,
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'reset':
      return initialState;
    case 'addTest':
      return {test: state.test + 1};
    case 'removeTest':
      return {test: state.test - 1};
  }
};

export const getReducer = () => {
  return useReducer(reducer, initialState);
};

现在,我可以在不同的渲染功能中通过getReducer获取状态并进行分派:

import React from 'react';
import ReactDOM from 'react-dom';

import {getReducer} from './reducer';

const Button = (props) => (
  <button
    type="button"
    onClick={() => props.dispatch({type: props.type})}>
    {props.children}
  </button>
);

const App = () => {
  const [state, dispatch] = getReducer();
  return (
    <React.Fragment>
      {state.test}
      <Button dispatch={dispatch} type="addTest">Add 1</Button>
      <Button dispatch={dispatch} type="removeTest">Remove 1</Button>
      <Button dispatch={dispatch} type="reset">Reset</Button>
    </React.Fragment>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

传递dispatch函数并让其他组件调用props.dispatch确实很奇怪。有没有更干净的方法进行设置?

如果您想尝试其他模式,请在此处设置一个仓库: https://github.com/dancrew32/hooks

1 个答案:

答案 0 :(得分:2)

如何定义您的操作并将其映射到化简器?

const mapDispatch => dispatch => ({
  reset: () => dispatch({ type: 'reset' }),
  addTest: () => dispatch({ type: 'addTest' }),
  removeTest: () => dispatch({ type: 'removeTest' })
})

const Button = (props) => (
  <button
    type="button"
    onClick={props.onClick}>
    {props.children}
  </button>
);

const App = () => {
  const [state, dispatch] = getReducer();
  const actions = mapDispatch(dispatch)
  return (
    <React.Fragment>
      {state.test}
      <Button onClick={actions.addTest}>Add 1</Button>
      <Button onClick={actions.removeTest}>Remove 1</Button>
      <Button onClick={actions.reset}>Reset</Button>
    </React.Fragment>
  );
};

这里没有新内容;只是react-redux做事方式的模仿。