包含useContext钩子会导致子级的useState重置为初始值 [英] Including useContext hook causes child's useState to reset to initial value

查看:18
本文介绍了包含useContext钩子会导致子级的useState重置为初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上挣扎了几天了,所以如果有任何帮助,我将不胜感激。我们有一个全局数据上下文,它包含在层次结构中的几个组件中。我已经复制了我们在下面的基本示例中看到的问题。

您还可以run it on CodeSandbox

问题是Content组件中的childValue在组件每次重新呈现时都被重置为其初始useState值。但当useData上下文位于Routes组件中的链上游时,才会出现这种情况。删除useData行(并硬编码isAuthenticated)可以解决问题。然而,这不是一个可接受的解决方案,因为我们需要能够在全球背景下保留某些价值观,并将它们包括在任何地方。

我尝试了在React.memo(...)中包装东西,但没有效果。我在这里错过了什么?

import React, { useState, useContext, useEffect } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { render } from "react-dom";

// Routes

const Routes = () => {
  // We see desired behavior if useData() is removed here.
  //  i.e. Initial Value does NOT get reset in Content
  const { isAuthenticated } = useData();
  // const isAuthenticated = true // uncomment this after removing the above line

  const RouteComponent = isAuthenticated ? PrivateRoute : Route;

  return (
    <Switch>
      <RouteComponent path="/" render={props => <Content {...props} />} />
    </Switch>
  );
};

const PrivateRoute = ({ render: Render, path, ...rest }) => (
  <Route
    path={path}
    render={props => <Render isPrivate={true} {...props} />}
    {...rest}
  />
);

// Data Context

export const DataContext = React.createContext();
export const useData = () => useContext(DataContext);
export const DataProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [contextValue, setContextValue] = useState(false);

  useEffect(() => {
    setIsAuthenticated(true);
  }, []);

  const doSomethingInContext = () => {
    setTimeout(() => setContextValue(!contextValue), 1000);
  };

  return (
    <DataContext.Provider
      value={{
        isAuthenticated,
        doSomethingInContext,
        contextValue
      }}
    >
      {children}
    </DataContext.Provider>
  );
};

// Page Content

const Content = props => {
  const { contextValue, doSomethingInContext } = useData();

  const [childValue, setChildValue] = useState("Initial Value");

  useEffect(() => {
    if (childValue === "Value set on Click") {
      doSomethingInContext();
      setChildValue("Value set in useEffect");
    }
  }, [childValue]);

  return (
    <div>
      <div style={{ fontFamily: "monospace" }}>contextValue:</div>
      <div>{contextValue.toString()}</div>
      <br />
      <div style={{ fontFamily: "monospace" }}>childValue:</div>
      <div>{childValue}</div>
      <br />
      <button onClick={() => setChildValue("Value set on Click")}>
        Set Child Value
      </button>
    </div>
  );
};

const App = () => {
  return (
    <DataProvider>
      <Router>
        <Routes />
      </Router>
    </DataProvider>
  );
};

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

推荐答案

我认为问题在于:当您调用doSomethingInContext时,它会触发setContextValue(超时后)。当它运行时,它会更新Provider的数据,这会导致Routes重新生成(因为它是使用者)。重新生成Routes会更改render函数,导致丢弃并重新生成下面的所有内容。尝试useCallback:在Routes中,添加以下内容:

// In the body...
const render = useCallback(
  props => <Content {...props} />,
  []
);

// In the RouteComponent
<RouteComponent path="/" render={render} />

这样,函数不会更改,并且子项应该在重建过程中保留。

这篇关于包含useContext钩子会导致子级的useState重置为初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆