简体   繁体   中英

How to use React.useReducer (or equivalent) in class component?

Is there any way to use useReducer or any equivalent thing in React native class Components?

Yeah reducer method is raw js function. Can we use it in class directly rather joining it with states of class?

function init(initialCount) {
  return {count: initialCount};
}

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':
      return init(action.payload);
    default:
      throw new Error();
  }
}

class App extends React.Component {
  ...
  render() {
    return(...)
  }
}

Create a wrapper component that uses the useReducer hook and pass the state and dispatch function as props.

Example:

const Wrapper = props => {
  const [state, dispatch] = useReducer(reducer, initialCount, init);

  return <App {...props} {...{ state, dispatch }} />;
};

This might be better abstracted into a reusable Higher Order Component though.

Example:

const withUseReducer = (...useReducerArgs) => Component => props => {
  const [state, dispatch] = useReducer(...useReducerArgs);

  return <Component {...props} {...{ state, dispatch }} />;
};

...

export default withUseReducer(reducer, initialCount, init)(App);

Consuming in class component:

class App extends React.Component {

  ...

  render() {
    const { state, dispatch } = this.props;

    ...

    return(...)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM