【问题标题】:window.location does not work with react app using react router 4window.location 不适用于使用反应路由器 4 的反应应用程序
【发布时间】:2017-10-10 17:26:41
【问题描述】:

具有以下“应用程序”,并且window.location 不可配置。理想情况下,我希望点击提交按钮并转到备用域。这实际上是一个更大的应用程序的一部分,在该应用程序中,我使用外部身份提供程序进行登录。下面的片段是一个完整的示例来说明这个问题:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import Router from './routes';
import reducers from './reducers';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

const store = createStore(reducers);

class Signin extends React.Component {
  onSubmit() {
    var result = Object.getOwnPropertyDescriptor(window, 'location');
    window.location = 'http://www.bbc.co.uk';
  }

  render() {
    return (
      <div>
        <form
          className="form-horizontal col-xs-10 col-xs-offset-1"
          onSubmit={this.onSubmit.bind(this)}
        >
          <div className="form-group">
            <span className="col-xs-3" />
            <div className="col-sm-6">
              <button type="submit" className="btn btn-success btn-sm">
                Submit
              </button>
            </div>
          </div>
        </form>
        <script />
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <div className="container">{this.props.children}</div>
      </div>
    );
  }
}

render(
  <Provider store={store}>
    <BrowserRouter>
      <App>
        <Switch>
          <Route exact path="/" component={Signin} />
        </Switch>
      </App>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

你可以看到working sample here

在我真正的“应用程序”上,我使用以下依赖项和版本:

 "prop-types": "^15.6.0"
  "react": "^15.6.1"
  "react-dom": "^15.6.1"
  "react-redux": "4.3.0"
  "react-router-dom": "^4.0.0"
  "react-scripts": "1.0.13"

你会注意到我输入了一行:

var result = Object.getOwnPropertyDescriptor(window, 'location');

这将返回有关location 对象的信息并指示configurable=false。该 URL 当前保持不变,并在末尾标记了 /?

谁能提供任何见解?也试过window.location.href。似乎反应/反应路由器正在将 window.location 重新配置为不可配置 - 任何人都可以提供任何理由或解决方法。

【问题讨论】:

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


    【解决方案1】:

    好的,我没有阻止表单提交。

     onSubmit(e) {
        e.preventDefault();
        window.location = "https://www.bbc.co.uk";
      }
    

    是的,又是那个……

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2021-01-21
      • 1970-01-01
      • 2020-02-19
      • 2020-11-01
      相关资源
      最近更新 更多