【问题标题】:React component State clears after adding additional query parameters to the URL向 URL 添加额外的查询参数后,React 组件状态清除
【发布时间】:2021-04-07 08:04:01
【问题描述】:

在我的项目中,我有一个可以在选项卡视图中填充数据的页面。因此,选定的选项卡将作为浏览器历史记录出现,然后下一页获取选定的选项卡。我正在从第 01 页发送以下信息。

return ['settings', 'details', 'content'].map((menuItem) => {
  return (
    <MenuItem
      key={menuItem}
      classes={{ root: classes.menuItemRoot }}
      onClick={() => {
        handleItemClick({
          pathname: '/courses/manage',
          state: {
            activeTab: menuItem, section, id, product
          }
        });
      }}
    >
      {formatMessage(messages[menuItem])}
    </MenuItem>
  );
});

然后页面 2 将从浏览器历史记录中捕获状态并根据所选选项卡加载内容。 URL 看起来像 /courses/manage

  const {
    state: {
      activeTab, section, id, product
    }
  } = browserHistory.getCurrentLocation();

那么即使我刷新页面后,状态也不会被清除。

但是当我添加像/courses/manage?locale=fr 这样的额外查询参数时,它会呈现一个空页面,因为状态已被清除。

所以,我的问题是,即使在更改 URL 之后,如何才能使第 2 页的状态保持静态。

【问题讨论】:

  • 即使在向当前 URL 添加了一些查询参数之后,我也希望保持状态/浏览器历史记录不变。

标签: reactjs debugging redux react-hooks state


【解决方案1】:

我不完全了解您想要做什么,但您可以使用浏览器历史记录的 replaceState method 将当前状态替换为没有 state 的版本。

react-router-dom 的方法如下:

// access the history object
const history = useHistory();

// replace the current location with one without state
const clearState = () => {
    // get the current location which includes the state
    const {state, ...location} = history.location;
    // drop the state property and replace
    history.replace(location);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多