【发布时间】: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