使用withRouter后,您不应在路由器外使用Route

时间:2019-05-27 14:00:25

标签: javascript reactjs react-router-dom

我必须在嵌套组件中使用this.props.history.push('/ ...'),所以我添加了 withRouter()来使用react-router-dom进行导航,而不会出现历史记录问题

但是,由于我已经添加了Router,所以出现了您不应在路由器外使用Route 错误。 我已经阅读了有关此错误的文章,但我不明白我的代码有什么问题。

Root.js:

import { BrowserRouter as Router, Route, Switch, Redirect, withRouter} from 'react-router-dom'
...
const Root = ({ store }) => (
          <Router>
            <Provider store={store}>
                <StripeProvider apiKey="pk_test_XXXXXXXXX">
                  <Switch>
                      <Route exact path="/" component={App} />
                      <Route path="/comp1" component={Comp1} />
                      <Route path="/comp2" component={Comp2} />
                      <Route path="/store" component={MyStoreCheckout} />
                      <Route component={Notfound} />
                  </Switch>
                </StripeProvider>
             </Provider>
          </Router>
)
Root.propTypes = {
  store: PropTypes.object.isRequired
}
export default withRouter(Root)

和index.js:

import { createStore } from 'redux'
import myReducer from './redux/Reducers/myReducer'
import Root from './Root'
import Store from './redux/Store/store'

render(<Root store={Store} />, document.getElementById('root'))

我使用withRouter能够在CheckoutForm中调用this.props.history(...) MyStoreCheckout.js:

class MyStoreCheckout extends React.Component {
  render() {
    return (
      <Elements>
        <InjectedCheckoutForm />
      </Elements>
    );
  }
}
export default MyStoreCheckout;

CheckoutForm.js:

class CheckoutForm extends React.Component {
  handleSubmit = () => {
    fetch(getRequest)
        .then((response) => response.json())
        .then(...)
        .then(() => this.goToSuccessPage())
  }

  goToSuccessPage(){
    this.props.history.push('/') ; //----- error is here if I have no withRouter

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <DetailsSection/>
        <CardSection />
        <button>Confirm order</button>
      </form>
    );
  }
}

export default injectStripe(CheckoutForm);

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的那样……只需将withRouter文件的顶部导入CheckoutForm,然后在其底部包装导出即可。像这样:

CheckoutForm.js:

import { withRouter} from 'react-router-dom'

class CheckoutForm extends React.Component {
  // ... your class code ...
}

export default withRouter(injectStripe(CheckoutForm));

如果您的injectStripe HOC没有将所有道具从withRouter传递到CheckoutForm,则可以尝试执行export default injectStripe(withRouter(CheckoutForm));,但是可以尝试order shouldn't matter (如果设置正确)