useOptimistic

useOptimistic 是一个 React Hook,可让你乐观地更新 UI。

¥useOptimistic is a React Hook that lets you optimistically update the UI.

const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);

参考

¥Reference

useOptimistic(state, updateFn)

useOptimistic 是一个 React Hook,可让你在异步操作正在进行时显示不同的状态。它接受某些状态作为参数,并返回该状态的副本,该副本在异步操作(例如网络请求)期间可能会有所不同。你提供一个函数,该函数接受当前状态和操作的输入,并返回操作待处理时要使用的乐观状态。

¥useOptimistic is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending.

此状态称为 “optimistic” 状态,因为它通常用于立即向用户渲染执行操作的结果,即使该操作实际上需要时间才能完成。

¥This state is called the “optimistic” state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.

import { useOptimistic } from 'react';

function AppContainer() {
const [optimisticState, addOptimistic] = useOptimistic(
state,
// updateFn
(currentState, optimisticValue) => {
// merge and return new state
// with optimistic value
}
);
}

请参阅下面的更多示例。

¥See more examples below.

参数

¥Parameters

  • state:最初以及每当没有待处理的操作时要返回的值。

    ¥state: the value to be returned initially and whenever no action is pending.

  • updateFn(currentState, optimisticValue):一个函数,它接受当前状态和传递给 addOptimistic 的乐观值并返回结果乐观状态。它必须是一个纯函数。updateFn 接受两个参数。currentStateoptimisticValue。返回值将是 currentStateoptimisticValue 的合并值。

    ¥updateFn(currentState, optimisticValue): a function that takes the current state and the optimistic value passed to addOptimistic and returns the resulting optimistic state. It must be a pure function. updateFn takes in two parameters. The currentState and the optimisticValue. The return value will be the merged value of the currentState and optimisticValue.

返回

¥Returns

  • optimisticState:由此产生的乐观状态。它等于 state,除非操作处于待处理状态,在这种情况下,它等于 updateFn 返回的值。

    ¥optimisticState: The resulting optimistic state. It is equal to state unless an action is pending, in which case it is equal to the value returned by updateFn.

  • addOptimisticaddOptimistic 是当你有乐观更新时要调用的调度函数。它接受一个任意类型的参数 optimisticValue,并将使用 stateoptimisticValue 调用 updateFn

    ¥addOptimistic: addOptimistic is the dispatching function to call when you have an optimistic update. It takes one argument, optimisticValue, of any type and will call the updateFn with state and optimisticValue.


用法

¥Usage

乐观地更新表单

¥Optimistically updating forms

useOptimistic 钩子提供了一种在后台操作(如网络请求)完成之前乐观地更新用户界面的方法。在表单环境中,此技术有助于使应用感觉更具响应性。当用户提交表单时,界面会立即更新为预期结果,而不是等待服务器的响应来反映更改。

¥The useOptimistic Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server’s response to reflect the changes, the interface is immediately updated with the expected outcome.

例如,当用户在表单中键入消息并点击 “发送” 按钮时,useOptimistic 钩子允许消息立即显示在带有 “正在发送…” 标签的列表中,甚至在消息实际发送到服务器之前也是如此。这种 “optimistic” 方法给人以速度和响应能力的印象。然后,该表单尝试在后台真正发送消息。一旦服务器确认已收到消息,“正在发送…” 标签就会被删除。

¥For example, when a user types a message into the form and hits the “Send” button, the useOptimistic Hook allows the message to immediately appear in the list with a “Sending…” label, even before the message is actually sent to a server. This “optimistic” approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the “Sending…” label is removed.

import { useOptimistic, useState, useRef } from "react";
import { deliverMessage } from "./actions.js";

function Thread({ messages, sendMessage }) {
  const formRef = useRef();
  async function formAction(formData) {
    addOptimisticMessage(formData.get("message"));
    formRef.current.reset();
    await sendMessage(formData);
  }
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (state, newMessage) => [
      ...state,
      {
        text: newMessage,
        sending: true
      }
    ]
  );

  return (
    <>
      {optimisticMessages.map((message, index) => (
        <div key={index}>
          {message.text}
          {!!message.sending && <small> (Sending...)</small>}
        </div>
      ))}
      <form action={formAction} ref={formRef}>
        <input type="text" name="message" placeholder="Hello!" />
        <button type="submit">Send</button>
      </form>
    </>
  );
}

export default function App() {
  const [messages, setMessages] = useState([
    { text: "Hello there!", sending: false, key: 1 }
  ]);
  async function sendMessage(formData) {
    const sentMessage = await deliverMessage(formData.get("message"));
    setMessages((messages) => [...messages, { text: sentMessage }]);
  }
  return <Thread messages={messages} sendMessage={sendMessage} />;
}


React 中文网 - 粤ICP备13048890号