【问题标题】:How can i Dynamically Update the React Helmet Value when state changes状态更改时如何动态更新 React 头盔值
【发布时间】:2022-11-29 17:05:29
【问题描述】:

我想动态更新 React Helmet 值,我在状态下尝试过,但是每当我更改页面时它都不会更新,而是显示旧值 我想为 SEO 添加一个元标记,规范标记和每个页面更改我都想更新它但是当我重新加载页面时它正在更新但不是在页面上使用 React Router 更改


function App() {
 
  const location = useLocation();
  const [canonical, setCanonical] = useState(window.location.href);

  useEffect(() => {
    setCanonical(window.location.href);
  }, [location]);

  return (
    <div className="App">
      <Helmet>
       
        <link rel="canonical" href={canonical} />
      </Helmet>
  

I tried with the following code present in my App.js file  I want to update it the canonical value when the state changes

【问题讨论】:

    标签: reactjs react-hooks react-helmet


    【解决方案1】:

    试试useLocation钩子来检测路由变化

    const location = useLocation();
    
    useEffect(() => {
      console.log('Location changed');
    }, [location]);
    

    【讨论】:

    • const location = useLocation(); const [canonical, setCanonical] = useState(window.location.href); useEffect(() => { // 使用浏览器 API 更新文档标题 setCanonical(window.location.href); }, [location]);我像这样使用它,它抛出错误 Uncaught Error: useLocation() may be used only in the context of a <Router> component。
    • 你在哪里定义Router
    • 请检查我这样使用的问题,我用整个文件编辑了问题
    • useLocation 可以在Router 级别内使用。您需要将 link 组件移动到 browser 路由内,并将 useLocation 移动到 app 组件内的子组件内
    猜你喜欢
    • 2017-03-22
    • 2020-05-08
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2020-11-11
    • 2018-09-21
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多