使用 Reducer 和上下文进行扩展

Reducers 让你整合组件的状态更新逻辑。Context 让你将信息传递到更深层的其他组件。你可以结合 reducers 和 context 一起管理复杂界面的状态。

🌐 Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen.

你将学习到

  • 如何将 reducer 与上下文结合起来
  • 如何避免通过属性传递状态和调度
  • 如何将上下文和状态逻辑保持在单独的文件中

结合 reducer 和上下文

🌐 Combining a reducer with context

在这个来自 reducers 介绍 的示例中,状态由一个 reducer 管理。reducer 函数包含所有状态更新的逻辑,并在此文件的底部声明:

🌐 In this example from the introduction to reducers, the state is managed by a reducer. The reducer function contains all of the state update logic and is declared at the bottom of this file:

import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(
    tasksReducer,
    initialTasks
  );

  function handleAddTask(text) {
    dispatch({
      type: 'added',
      id: nextId++,
      text: text,
    });
  }

  function handleChangeTask(task) {
    dispatch({
      type: 'changed',
      task: task
    });
  }

  function handleDeleteTask(taskId) {
    dispatch({
      type: 'deleted',
      id: taskId
    });
  }

  return (
    <>
      <h1>Day off in Kyoto</h1>
      <AddTask
        onAddTask={handleAddTask}
      />
      <TaskList
        tasks={tasks}
        onChangeTask={handleChangeTask}
        onDeleteTask={handleDeleteTask}
      />
    </>
  );
}

function tasksReducer(tasks, action) {
  switch (action.type) {
    case 'added': {
      return [...tasks, {
        id: action.id,
        text: action.text,
        done: false
      }];
    }
    case 'changed': {
      return tasks.map(t => {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case 'deleted': {
      return tasks.filter(t => t.id !== action.id);
    }
    default: {
      throw Error('Unknown action: ' + action.type);
    }
  }
}

let nextId = 3;
const initialTasks = [
  { id: 0, text: 'Philosopher’s Path', done: true },
  { id: 1, text: 'Visit the temple', done: false },
  { id: 2, text: 'Drink matcha', done: false }
];

一个 reducer 有助于保持事件处理函数简短而简洁。然而,随着应用的增长,你可能会遇到另一个困难。目前,tasks 状态和 dispatch 函数只能在顶层的 TaskApp 组件中使用。 为了让其他组件能够读取任务列表或修改它,你必须明确地向下传递当前的状态以及修改状态的事件处理函数作为 props。

🌐 A reducer helps keep the event handlers short and concise. However, as your app grows, you might run into another difficulty. Currently, the tasks state and the dispatch function are only available in the top-level TaskApp component. To let other components read the list of tasks or change it, you have to explicitly pass down the current state and the event handlers that change it as props.

例如,TaskApp 将任务列表和事件处理程序传递给 TaskList

🌐 For example, TaskApp passes a list of tasks and the event handlers to TaskList:

<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeleteTask}
/>

并且 TaskList 将事件处理程序传递给 Task

🌐 And TaskList passes the event handlers to Task:

<Task
task={task}
onChange={onChangeTask}
onDelete={onDeleteTask}
/>

在像这样的小示例中,这很有效,但是如果中间有数十个或数百个组件,传递所有状态和函数可能会非常令人沮丧!

🌐 In a small example like this, this works well, but if you have tens or hundreds of components in the middle, passing down all state and functions can be quite frustrating!

这就是为什么,作为一种替代通过 props 传递它们的方法,你可能希望将 tasks 状态和 dispatch 函数 放入上下文中。 这样,树中 TaskApp 以下的任何组件都可以读取任务并分发操作,而无需重复的“prop 传递”。

🌐 This is why, as an alternative to passing them through props, you might want to put both the tasks state and the dispatch function into context. This way, any component below TaskApp in the tree can read the tasks and dispatch actions without the repetitive “prop drilling”.

以下是如何将 reducer 与上下文结合起来:

🌐 Here is how you can combine a reducer with context:

  1. 创建上下文。
  2. state 和 dispatch 放入上下文中。
  3. 在树的任何地方使用上下文。

步骤 1:创建上下文

🌐 Step 1: Create the context

useReducer 钩子返回当前的 tasks 以及可以更新它们的 dispatch 函数:

🌐 The useReducer Hook returns the current tasks and the dispatch function that lets you update them:

const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

要将它们传递下树,你将创建两个独立的上下文:

🌐 To pass them down the tree, you will create two separate contexts:

  • TasksContext 提供当前的任务列表。
  • TasksDispatchContext 提供了让组件分发动作的功能。

从单独的文件中导出它们,以便以后可以从其他文件中导入它们:

🌐 Export them from a separate file so that you can later import them from other files:

import { createContext } from 'react';

export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);

在这里,你将 null 作为默认值传递给两个上下文。实际的值将由 TaskApp 组件提供。

🌐 Here, you’re passing null as the default value to both contexts. The actual values will be provided by the TaskApp component.

步骤 2:将 state 和 dispatch 放入上下文

🌐 Step 2: Put state and dispatch into context

现在你可以在你的 TaskApp 组件中导入这两个上下文。获取由 useReducer() 返回的 tasksdispatch 并将它们 提供 给下面的整个树:

🌐 Now you can import both contexts in your TaskApp component. Take the tasks and dispatch returned by useReducer() and provide them to the entire tree below:

import { TasksContext, TasksDispatchContext } from './TasksContext.js';

export default function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
// ...
return (
<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>
...
</TasksDispatchContext>
</TasksContext>
);
}

现在,你通过属性和上下文传递信息:

🌐 For now, you pass the information both via props and in context:

import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import { TasksContext, TasksDispatchContext } from './TasksContext.js';

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(
    tasksReducer,
    initialTasks
  );

  function handleAddTask(text) {
    dispatch({
      type: 'added',
      id: nextId++,
      text: text,
    });
  }

  function handleChangeTask(task) {
    dispatch({
      type: 'changed',
      task: task
    });
  }

  function handleDeleteTask(taskId) {
    dispatch({
      type: 'deleted',
      id: taskId
    });
  }

  return (
    <TasksContext value={tasks}>
      <TasksDispatchContext value={dispatch}>
        <h1>Day off in Kyoto</h1>
        <AddTask
          onAddTask={handleAddTask}
        />
        <TaskList
          tasks={tasks}
          onChangeTask={handleChangeTask}
          onDeleteTask={handleDeleteTask}
        />
      </TasksDispatchContext>
    </TasksContext>
  );
}

function tasksReducer(tasks, action) {
  switch (action.type) {
    case 'added': {
      return [...tasks, {
        id: action.id,
        text: action.text,
        done: false
      }];
    }
    case 'changed': {
      return tasks.map(t => {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case 'deleted': {
      return tasks.filter(t => t.id !== action.id);
    }
    default: {
      throw Error('Unknown action: ' + action.type);
    }
  }
}

let nextId = 3;
const initialTasks = [
  { id: 0, text: 'Philosopher’s Path', done: true },
  { id: 1, text: 'Visit the temple', done: false },
  { id: 2, text: 'Drink matcha', done: false }
];

在下一步中,你将删除属性传递。

🌐 In the next step, you will remove prop passing.

步骤 3:在树的任何地方使用上下文

🌐 Step 3: Use context anywhere in the tree

现在你不需要将任务列表或事件处理程序向下传递到树中:

🌐 Now you don’t need to pass the list of tasks or the event handlers down the tree:

<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>
<h1>Day off in Kyoto</h1>
<AddTask />
<TaskList />
</TasksDispatchContext>
</TasksContext>

相反,任何需要任务列表的组件都可以从 TasksContext 读取它:

🌐 Instead, any component that needs the task list can read it from the TasksContext:

export default function TaskList() {
const tasks = useContext(TasksContext);
// ...

要更新任务列表,任何组件都可以从上下文中读取 dispatch 函数并调用它:

🌐 To update the task list, any component can read the dispatch function from context and call it:

export default function AddTask() {
const [text, setText] = useState('');
const dispatch = useContext(TasksDispatchContext);
// ...
return (
// ...
<button onClick={() => {
setText('');
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}}>Add</button>
// ...

TaskApp 组件不会传递任何事件处理程序,而 TaskList 也不会将任何事件处理程序传递给 Task 组件。 每个组件都会读取它所需要的上下文:

import { useState, useContext } from 'react';
import { TasksContext, TasksDispatchContext } from './TasksContext.js';

export default function TaskList() {
  const tasks = useContext(TasksContext);
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          <Task task={task} />
        </li>
      ))}
    </ul>
  );
}

function Task({ task }) {
  const [isEditing, setIsEditing] = useState(false);
  const dispatch = useContext(TasksDispatchContext);
  let taskContent;
  if (isEditing) {
    taskContent = (
      <>
        <input
          value={task.text}
          onChange={e => {
            dispatch({
              type: 'changed',
              task: {
                ...task,
                text: e.target.value
              }
            });
          }} />
        <button onClick={() => setIsEditing(false)}>
          Save
        </button>
      </>
    );
  } else {
    taskContent = (
      <>
        {task.text}
        <button onClick={() => setIsEditing(true)}>
          Edit
        </button>
      </>
    );
  }
  return (
    <label>
      <input
        type="checkbox"
        checked={task.done}
        onChange={e => {
          dispatch({
            type: 'changed',
            task: {
              ...task,
              done: e.target.checked
            }
          });
        }}
      />
      {taskContent}
      <button onClick={() => {
        dispatch({
          type: 'deleted',
          id: task.id
        });
      }}>
        Delete
      </button>
    </label>
  );
}

状态仍然“存在”于顶层的 TaskApp 组件中,由 useReducer 管理。 但是其 tasksdispatch 现在可通过导入并使用这些上下文在组件树下的每个组件中使用。

将所有线路移动到一个文件中

🌐 Moving all wiring into a single file

你不必这样做,但你可以通过将 reducer 和 context 都移到一个文件中来进一步简化组件。目前,TasksContext.js 仅包含两个 context 声明:

🌐 You don’t have to do this, but you could further declutter the components by moving both reducer and context into a single file. Currently, TasksContext.js contains only two context declarations:

import { createContext } from 'react';

export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);

这个文件即将变得拥挤!你将把 reducer 移动到同一个文件中。然后你将在同一个文件中声明一个新的 TasksProvider 组件。这个组件将把所有部分联系在一起:

🌐 This file is about to get crowded! You’ll move the reducer into that same file. Then you’ll declare a new TasksProvider component in the same file. This component will tie all the pieces together:

  1. 它将使用 reducer 管理状态。
  2. 它将为下面的组件提供这两种上下文。
  3. 它将 children 作为一个 prop,所以你可以向它传递 JSX。
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

return (
<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>
{children}
</TasksDispatchContext>
</TasksContext>
);
}

这将移除你 TaskApp 组件中的所有复杂性和布线:

import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import { TasksProvider } from './TasksContext.js';

export default function TaskApp() {
  return (
    <TasksProvider>
      <h1>Day off in Kyoto</h1>
      <AddTask />
      <TaskList />
    </TasksProvider>
  );
}

你也可以导出从 TasksContext.js 使用上下文的函数:

🌐 You can also export functions that use the context from TasksContext.js:

export function useTasks() {
return useContext(TasksContext);
}

export function useTasksDispatch() {
return useContext(TasksDispatchContext);
}

当一个组件需要读取上下文时,它可以通过这些函数来完成:

🌐 When a component needs to read context, it can do it through these functions:

const tasks = useTasks();
const dispatch = useTasksDispatch();

这不会以任何方式改变行为,但它允许你以后进一步拆分这些上下文或向这些函数添加一些逻辑。现在所有的上下文和 reducer 连接都在 TasksContext.js 中。这使组件保持干净且不混乱,专注于它们显示的内容,而不是数据的来源:

🌐 This doesn’t change the behavior in any way, but it lets you later split these contexts further or add some logic to these functions. Now all of the context and reducer wiring is in TasksContext.js. This keeps the components clean and uncluttered, focused on what they display rather than where they get the data:

import { useState } from 'react';
import { useTasks, useTasksDispatch } from './TasksContext.js';

export default function TaskList() {
  const tasks = useTasks();
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          <Task task={task} />
        </li>
      ))}
    </ul>
  );
}

function Task({ task }) {
  const [isEditing, setIsEditing] = useState(false);
  const dispatch = useTasksDispatch();
  let taskContent;
  if (isEditing) {
    taskContent = (
      <>
        <input
          value={task.text}
          onChange={e => {
            dispatch({
              type: 'changed',
              task: {
                ...task,
                text: e.target.value
              }
            });
          }} />
        <button onClick={() => setIsEditing(false)}>
          Save
        </button>
      </>
    );
  } else {
    taskContent = (
      <>
        {task.text}
        <button onClick={() => setIsEditing(true)}>
          Edit
        </button>
      </>
    );
  }
  return (
    <label>
      <input
        type="checkbox"
        checked={task.done}
        onChange={e => {
          dispatch({
            type: 'changed',
            task: {
              ...task,
              done: e.target.checked
            }
          });
        }}
      />
      {taskContent}
      <button onClick={() => {
        dispatch({
          type: 'deleted',
          id: task.id
        });
      }}>
        Delete
      </button>
    </label>
  );
}

你可以将 TasksProvider 看作屏幕的一部分,它知道如何处理任务,将 useTasks 看作读取任务的一种方式,而将 useTasksDispatch 看作从树中任何下层组件更新任务的一种方式。

🌐 You can think of TasksProvider as a part of the screen that knows how to deal with tasks, useTasks as a way to read them, and useTasksDispatch as a way to update them from any component below in the tree.

注意

useTasksuseTasksDispatch 这样的函数被称为 自定义 Hook. 如果一个函数的名称以 use 开头,则该函数被认为是自定义 Hook。这让你可以在其中使用其他 Hook,例如 useContext

🌐 Functions like useTasks and useTasksDispatch are called Custom Hooks. Your function is considered a custom Hook if its name starts with use. This lets you use other Hooks, like useContext, inside it.

随着你的应用的发展,你可能会有许多像这样的上下文-Reducer 对。这是一种强大的方式来扩展你的应用,并在你想要访问树深处的数据时,不需要太多工作就能提升状态

🌐 As your app grows, you may have many context-reducer pairs like this. This is a powerful way to scale your app and lift state up without too much work whenever you want to access the data deep in the tree.

回顾

  • 你可以将 reducer 与上下文结合起来,让任何组件读取和更新其上方的状态。
  • 为以下组件提供状态和调度函数:
    1. 创建两个上下文(用于状态和调度函数)。
    2. 从使用 reducer 的组件中提供两个上下文。
    3. 使用来自需要读取它们的组件的任一上下文。
  • 你可以通过将所有线路移动到一个文件中来进一步整理组件。
    • 你可以导出一个像 TasksProvider 的提供上下文的组件。
    • 你也可以导出自定义 Hooks,例如 useTasksuseTasksDispatch 来读取它。
  • 你的应用中可以有很多这样的上下文-reducer 对。