【问题标题】:Passing state vs using context in react hooks在反应钩子中传递状态与使用上下文
【发布时间】:2020-06-23 00:21:40
【问题描述】:

我正在通过 video 探索 useContext 反应钩子

在这个视频中,他们所做的基本上是创建一个上下文

context.js

import { createContext } from "react";

export const CustomerContext = createContext(null);

并将这些上下文传递给子组件

import Table from "./components/table";
import React, { useState } from "react";
import { CustomerContext } from "./context";
const App = () => {
  const [user, setUser] = useState(null);
  return (
    <div>
      <p> Hello World</p>
      <CustomerContext.Provider value={{ user, setUser }}>
        <Table />
      </CustomerContext.Provider>
    </div>
  );
};

export default App;

然后在子组件中访问值或者改变值

import { CustomerContext } from "./../context";
import React, { useContext } from "react";

const Table = () => {
  const { user, setUser } = useContext(CustomerContext);

  return (
    <div>
      <p onClick={() => setUser("Rohit")}>Current User: {user}</p>
    </div>
  );
};

export default Table;

这也可以通过简单地将状态作为道具传递给子组件来实现。

那么使用useContext有什么好处呢?或者我可能误解了视频。

有人可以帮我吗?

【问题讨论】:

  • 当孩子从你的App 组件中嵌套几个父母时,使用上下文很好,因为你不必通过每个组件记住传递道具。您只需在需要的地方访问它
  • 这是唯一的优势吗?
  • 不,还有其他优点,但您应该阅读文档以深入比较利弊。这是一个常见的用例,这就是我提出它的原因。通常,它是处理应用程序中数据的一种更稳健的方式。

标签: reactjs react-hooks


【解决方案1】:

它避免了支柱钻孔。当你有 4 或 5 个嵌套组件时通过 props 传递数据是很糟糕的,这只是一个小例子。 Context 将允许您从应用程序中的任何位置获取数据,同时还提供了一种使用其他方法(如 dispatchuseReducer)管理数据的好方法。

此外,React 提供的 ContextApi 允许您创建多个上下文来分离您的关注点,我认为当您拥有大量数据时这非常酷。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 2021-07-31
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2021-07-28
    • 2021-08-25
    • 2021-02-11
    相关资源
    最近更新 更多