【问题标题】:How trigger function after react context hook updated反应上下文挂钩更新后如何触发功能
【发布时间】:2021-10-17 00:20:15
【问题描述】:

我正在尝试在 react 的“上下文挂钩”更新后调用一个函数。试了下面的代码:

const MyComponent = () => {
  [context] = useContext(MyContext);
  
  function updateContext():void {
    context = "someNewContext";
  }
  
  function anotherFunction():void {
    console.log("success!");
  }
  
  useEffect(() => {
    anotherFunction();
  }, [context]);
  
  return (
    <button onClick={updateContext}>update</button>
  );
}

export default MyComponent;

【问题讨论】:

  • 反应更新中的上下文挂钩是什么意思? . react 中的上下文值是一个对象。而且您也不会像在 updateContext 方法中那样直接改变上下文值。我们想在这里实现什么目标?

标签: reactjs react-hooks use-effect use-context


【解决方案1】:

现在我知道出了什么问题...首先我需要一个带有 useState 的包装器,如下所示:

const App = () => {
  const [context, setContext] = useState("initial value");
  const value = { context, setContext };

  return (
    <MyContext.Provider value={value}>
      <MyComponent />
    </MyContext.Provider>
  );
};

然后在组件上:

const MyComponent = () => {
  {context, setContext} = useContext(MyContext);

  function updateContext():void {
    setContext("Some new context");
  }

  function anotherFunction():void {
    console.log("success!");
  }

  useEffect(() => {
    anotherFunction();
  }, [context]);

  return (
    <button onClick={() => {updateContext()}}>update</button>
  );
}

export default MyComponent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2019-05-03
    • 2022-09-26
    • 1970-01-01
    • 2021-07-24
    • 2020-12-15
    • 2019-07-31
    相关资源
    最近更新 更多