React

梗概

  • consolidate all the state update logic outside your component in a single function, called “reducer”
  • 通常可以将reducer通过[use::context]共享出去

示例

定义reducer

// reducer.js
 
const initialState = {
  count: 0,
  isLoggedIn: false,
};
 
const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'LOGIN':
      return { ...state, isLoggedIn: true };
    case 'LOGOUT':
      return { ...state, isLoggedIn: false };
    default:
      return state;
  }
};
 
export { initialState, reducer };

In this example, we have defined an initial state object and a reducer function that takes the current state and an action as arguments. The reducer function then switches on the action type to determine how to update the state. Finally, we export both the initial state and the reducer function for use in our components.

使用reducer

// App.js
 
import React, { useReducer } from 'react';
import { initialState, reducer } from './reducer';
 
const App = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
 
  return (
    <div>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
      <br />
      <h2>{state.isLoggedIn ? "You are logged in" : "Please log in"}</h2>
      <button onClick={() => dispatch({ type: state.isLoggedIn ? 'LOGOUT' : 'LOGIN' })}>
        {state.isLoggedIn ? "Logout" : "Login"}
      </button>
    </div>
  );
};
 
export default App;

Here, we import the initial state and reducer function from the reducer.js file. We then use the useReducer hook to create a state and dispatch function based on our reducer. In the component, we can now update the state by calling dispatch with an action object that includes a type key to indicate which action to perform.

By using a reducer, we can centralize our state update logic and keep our components more focused on rendering UI rather than managing state. This can lead to more maintainable and predictable code.