如何在类组件中使用 React.useReducer (或等效项)?

Cra*_*KSR 5 reactjs react-native react-hooks react-reducer

useReducer在 React 原生类组件中有什么方法可以使用或任何等效的东西吗?

是的,reducer 方法是原始的 js 函数。我们可以直接在课堂上使用它而不是将它与课堂状态结合起来吗?

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(...)
  }
}
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 5

创建一个使用useReducer钩子的包装组件并将state和dispatch函数作为 props 传递。

例子:

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

  return <App {...props} {...{ state, dispatch }} />;
};
Run Code Online (Sandbox Code Playgroud)

不过,这可能更好地抽象为可重用的高阶组件。

例子:

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

  return <Component {...props} {...{ state, dispatch }} />;
};
Run Code Online (Sandbox Code Playgroud)

...

export default withUseReducer(reducer, initialCount, init)(App);
Run Code Online (Sandbox Code Playgroud)

在类组件中使用:

class App extends React.Component {

  ...

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

    ...

    return(...)
  }
}
Run Code Online (Sandbox Code Playgroud)