在当前版本的React Router (v3)中,我可以接受服务器响应并使用browserHistory。点击进入相应的响应页面。但是,这在v4中是不可用的,我不确定处理它的适当方法是什么。

在这个例子中,使用Redux, components/app-product-form.js在用户提交表单时调用this.props. addproduct (props)。当服务器返回成功时,用户将被带到Cart页面。

// actions/index.js
export function addProduct(props) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
      .then(response => {
        dispatch({ type: types.AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/cart'); // no longer in React Router V4
      });
}

如何从React Router v4的函数重定向到购物车页面?


当前回答

使用回调。这对我很管用!

export function addProduct(props, callback) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
    .then(response => {
    dispatch({ type: types.AUTH_USER });
    localStorage.setItem('token', response.data.token);
    callback();
  });
}

在组件中,你只需要添加回调

this.props.addProduct(props, () => this.props.history.push('/cart'))

其他回答

注意不要将react-router@5.2.0或react-router-dom@5.2.0与history@5.0.0连用。URL将在历史记录之后更新。推送或任何其他推送到历史指令,但导航不适用于react-router。使用NPM install history@4.10.1更改历史版本。参见升级到v5后,React路由器无法工作。

我认为这个问题发生在推动历史发生的时候。例如,使用<NavLink to="/apps">时,NavLink.js会消耗<RouterContext.Consumer>. js。上下文。当推送到历史记录时,位置将更改为具有动作和位置属性的对象。所以currentLocation。Pathname为空以匹配路径。

你可以像我这样使用它来登录和曼尼不同的东西

class Login extends Component {
  constructor(props){
    super(props);
    this.login=this.login.bind(this)
  }


  login(){
this.props.history.push('/dashboard');
  }


render() {

    return (

   <div>
    <button onClick={this.login}>login</login>
    </div>

)
/*Step 1*/
myFunction(){  this.props.history.push("/home"); }
/**/
 <button onClick={()=>this.myFunction()} className={'btn btn-primary'}>Go 
 Home</button>

如果你想在将一个函数作为一个值传递给组件的prop时使用历史,使用react-router 4,你可以简单地在<Route/>组件的渲染属性中解构历史prop,然后使用history.push()

    <Route path='/create' render={({history}) => (
      <YourComponent
        YourProp={() => {
          this.YourClassMethod()
          history.push('/')
        }}>
      </YourComponent>
    )} />

注意:要做到这一点,你应该把React Router的BrowserRouter组件包裹在你的根组件(例如。可能在index.js中)

我再提供一个解决方案,以防它对其他人有用。

我有一个history.js文件,其中我有以下内容:

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history

接下来,在我定义路由器的根目录上,我使用以下命令:

import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'

export default class Root extends React.Component {
  render() {
    return (
     <Provider store={store}>
      <Router history={history}>
       <Switch>
        ...
       </Switch>
      </Router>
     </Provider>
    )
   }
  }

最后,在我的actions.js中,我导入历史并使用pushLater

import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)

这样,我可以在API调用之后推送到新的操作。

希望能有所帮助!