React useDelayedState 钩子

ReactReactBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何在 React 中使用 useDelayedState 钩子,以便在满足特定条件之前延迟创建有状态值。当我们需要在创建有状态值之前等待数据或属性加载时,此钩子非常有用,并且可以帮助提高应用程序的性能。通过实际示例,我们将了解如何实现此钩子以及如何在 React 组件中使用它来更新有状态值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react(("React")) -.-> react/StateManagementGroup(["State Management"]) react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/FundamentalsGroup -.-> react/state_lifecycle("State and Lifecycle") react/FundamentalsGroup -.-> react/event_handling("Handling Events") react/FundamentalsGroup -.-> react/list_keys("Lists and Keys") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") react/StateManagementGroup -.-> react/use_state_reducer("Using useState and useReducer") subgraph Lab Skills react/jsx -.-> lab-38380{{"React useDelayedState 钩子"}} react/state_lifecycle -.-> lab-38380{{"React useDelayedState 钩子"}} react/event_handling -.-> lab-38380{{"React useDelayedState 钩子"}} react/list_keys -.-> lab-38380{{"React useDelayedState 钩子"}} react/hooks -.-> lab-38380{{"React useDelayedState 钩子"}} react/use_state_reducer -.-> lab-38380{{"React useDelayedState 钩子"}} end

React useDelayedState 钩子

虚拟机中已提供 index.htmlscript.js。一般来说,你只需在 script.jsstyle.css 中添加代码。

要在满足条件之前延迟创建有状态值,请执行以下步骤:

  1. 使用 useState() 钩子创建一个包含实际 state 和布尔值 loaded 的有状态值。
  2. 如果 conditionloaded 发生变化,使用 useEffect() 钩子更新有状态值。
  3. 创建一个函数 updateState,仅在 loaded 为真值时更新 state 值。
const useDelayedState = (initialState, condition) => {
  const [{ state, loaded }, setState] = React.useState({
    state: null,
    loaded: false
  });

  React.useEffect(() => {
    if (!loaded && condition) setState({ state: initialState, loaded: true });
  }, [condition, loaded]);

  const updateState = (newState) => {
    if (!loaded) return;
    setState({ state: newState, loaded });
  };

  return [state, updateState];
};

以下是如何使用 useDelayedState 钩子的示例:

const App = () => {
  const [branches, setBranches] = React.useState([]);
  const [selectedBranch, setSelectedBranch] = useDelayedState(
    branches[0],
    branches.length
  );

  React.useEffect(() => {
    const handle = setTimeout(() => {
      setBranches(["master", "staging", "test", "dev"]);
    }, 2000);
    return () => {
      handle && clearTimeout(handle);
    };
  }, []);

  return (
    <div>
      <p>Selected branch: {selectedBranch}</p>
      <select onChange={(e) => setSelectedBranch(e.target.value)}>
        {branches.map((branch) => (
          <option key={branch} value={branch}>
            {branch}
          </option>
        ))}
      </select>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

请点击右下角的“Go Live”以在端口 8080 上运行 Web 服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了 React useDelayedState 钩子实验。你可以在 LabEx 中练习更多实验来提升你的技能。