Лучший способ настроить React useReducer - PullRequest
0 голосов
/ 05 ноября 2018

Я установил этот файл reducer.js для использования React's 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 голосов
/ 05 ноября 2018

Как насчет определения ваших действий и сопоставления их с вашим редуктором?

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 делает вещи.

...