首页 > 解决方案 > 如何在反应中切换下拉列表时更新 URL

问题描述

我正在尝试根据下拉列表的值更新 URL。通过什么功能可以更新网址。

 handleChange = (e) => {
      // update client code
      this.setState({ clientcode: e.target.value.substr(0, 5),
        value: e.target.value,
      });
      // now update url
      // this.props.history.push('/v4/adminv2/web.php/client-onboard/family-management/api/packet?clientcode=' + this.state.clientcode);
      const state = "";
      const title = "";
      const url = '/v4/adminv2/web.php/client-onboard/family-management/api/packet?clientcode=' + this.state.clientcode;
      window.history.pushState(state, title, url);
    }

对于下拉列表中的每次更改,都需要更新 URL 中的 this.state.clientcode 并重新加载页面。

下拉值更改后,无法看到 url 的任何更改。

标签: reactjsreact-router

解决方案


您可以使用从路由器传递的历史对象:

handleChange = (e) => {
  this.setState({ 
    clientcode: e.target.value.substr(0, 5),
    value: e.target.value,
  });
  const url = `/v4/adminv2/web.php/client-onboard/family-management/api/packet?clientcode=${this.state.clientcode}`
  props.history.push(url);
}

这不会重新加载页面


推荐阅读