【问题标题】:Does a React Context update on history.push('/')是否在 history.push('/') 上更新 React Context
【发布时间】:2021-06-26 17:36:39
【问题描述】:

我正在使用带有 useEffect 钩子的 React Context const Context = React.createContext() 在包装整个应用程序的最外层组件中设置一个变量。在我的应用程序中的一个子组件上,我使用history.push('/') 路由回根。这似乎会触发我的 Context 变量的更新。这是预期的吗?如果是这样,是否有更好的路由方法来更新我的上下文变量?

我正在使用react 16.14.0 & react-router-dom 5.2.0

例如,在下面的代码中。 var 不应该在 history.push('/') 上增加

Context.js

const Context= React.createContext();

const ContextProvider= (props) => {
  const [var, setVar] = useState(null);

  useEffect(() => {
    setVar(var++)
  }, []);

  return (
    <Context.Provider value={user}>{props.children}</Context.Provider>
  );
};

ChildComponent.js

...
import { useHistory } from "react-router-dom";
...

const ChildComponent = () => {
  const history = useHistory();

  function doSomething(){
    history.push('/')
  }
}
return(
    <Button onClick={() => doSomething()} />
)

【问题讨论】:

  • 分享一些示例代码

标签: reactjs react-router react-hooks react-router-dom


【解决方案1】:

这似乎不会触发我的 Context 变量的更新。这是预期的吗?

更改历史不会导致上下文提供程序重新呈现。你提到你有一个useEffect,原则上你可以在那个useEffect中编写一些代码来监听历史,当它发生变化时,它会设置状态以导致重新渲染。如果您认为其中的代码应该监听历史更改,请随时分享,我会对此发表评论。

但是,我建议使用hooks provided by react-router,而不是编写自己的代码来监听更改。 useHistoryuseLocation 钩子都会监听变化并重新渲染组件。

const Example = () => {
  // When the location changes, Example will rerender
  const location = useLocation();
  const [someState, setSomeState] = useState('foo');

  useEffect(() => {
    if (/* check something you care about in the location */) {
      setSomeState('bar');
    }
  }, [location]);

  return (
    <Context.Provider value={someState}>
      {children}
    </Context.Provider>
  )
}

【讨论】:

  • 感谢您的回答!我已经用一些示例代码更新了问题。您已经回答了我的问题,但请随时根据我更新的代码示例提出建议。
猜你喜欢
  • 2018-09-30
  • 2021-05-17
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
相关资源
最近更新 更多