React Router v4中history.replace报错及Redux组件内重定向问题
history.location.replace is not a function in React Router v4 + Redux Hey there, I’ve run into this exact issue before—let’s break down what’s going wrong and how to fix it step by step.
First: The Direct Error Cause
The core mistake here is that you’re calling replace on history.location, but replace is a method of the history object itself, not the location property.
history.location is just a plain object holding info about the current route path, params, etc.—it doesn’t have a replace method. The correct call is history.replace('/path').
Second: Make Sure Your Component Has Access to history
Since your component is connected to Redux with connect, it might not receive the history prop automatically (this happens if the component isn’t directly rendered by a <Route> component). To fix this, wrap your connected component with the withRouter higher-order component from React Router:
import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; class YourAuthComponent extends React.Component { // Updated lifecycle method (see note below about deprecated methods) componentDidUpdate(prevProps) { // Check if auth state changed to authenticated if (this.props.user.isAuthenticated !== prevProps.user.isAuthenticated && this.props.user.isAuthenticated) { // Correct way to call replace this.props.history.replace('/dashboard'); } } // ... rest of your component code } const mapStateToProps = (state) => ({ user: state.user }); // Wrap connect with withRouter to inject history props export default withRouter(connect(mapStateToProps)(YourAuthComponent));
Bonus: Use Modern Lifecycle Methods
Quick heads-up: componentWillReceiveProps is deprecated in React 16.3+. For side effects like redirecting when props change, componentDidUpdate is the recommended lifecycle method (as shown in the code above). It’s safer and aligns with React’s current best practices.
Verify the history Object
If you still run into issues, log this.props.history (or nextProps.history) again—you should see a replace method directly on the object, along with push, goBack, etc. If you don’t see these methods, double-check that withRouter is correctly wrapping your connected component (the order matters: withRouter goes around the connect call, not the other way around).
内容的提问来源于stack exchange,提问作者Madeline Ries

