【问题标题】:Why history push(query params) reloads the page? React为什么历史推送(查询参数)会重新加载页面?反应
【发布时间】:2020-05-21 04:22:23
【问题描述】:

问题:当我尝试通过添加查询参数来更新 url 时,页面会重新加载。

.tsx

useEffect(() => {
  requestResources()
  requestPosts({})
}, [])

const handleSlideItemClick = (value: string) => {
  history.push(`?resource=${value}`)
}

return (
  Box py={16} px='8px'>
    <SmoothSlider
      list={resources.list}
      name='resource'
      onSelect={handleSlideItemClick}
    />
  </Box>
)

期望:只需通过添加查询参数来更新 url 而无需重新加载页面

我也试过&lt;Link to={?resource=&{someValue}}&gt;,结果是一样的。

【问题讨论】:

  • 当您说页面重新加载时,您的意思是组件重新安装吗?您的想法是否只是将新的查询参数添加到 url
  • @ShubhamKhatri 是的,这就是我想要的
  • 您能否为您的应用程序创建一个可重现的演示,因为它确实可以按您的预期工作

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


【解决方案1】:

您可以使用 pushState 来实现此功能。更新查询 URL 时不会重新加载 URL。

你可以这样实现:

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?resource=newValue';

history.pushState({path:newurl},'',newurl);

newurl 是您更新后的网址。

Source

【讨论】:

    【解决方案2】:

    您应该尝试使用&lt;Link /&gt; 并将属性to 设置为function

    <Link to={location => ({ ...location, search: `?resource=${value}` })} />
    

    【讨论】:

      【解决方案3】:

      试试这个代码 sn-p。按下按钮后,“值”保持在 React 状态并正确传递到 URL,并且不会重新加载 React 代码。

      import  React, {useState}  from 'react';
      
      // https://stackoverflow.com/questions/61927235/why-history-pushquery-params-reloads-the-page-react
      export default function App(props) {
      
      
          const [value, setValue] = useState(0)
      
          function handleSlideItemClick(target) {
              setValue( value + 1);
              // eslint-disable-next-line no-restricted-globals
              history.pushState ({ }, 'Page Title', `?resource=${value}`)
          }
          // I am using  button for simplicity 
          return <button type="button" onClick={handleSlideItemClick}>Click Me!</button>
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-09
        • 2018-01-04
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        • 2020-12-13
        • 1970-01-01
        相关资源
        最近更新 更多