在当前版本的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的函数重定向到购物车页面?


当前回答

注意不要将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为空以匹配路径。

其他回答

根据React Router v4文档- Redux深度集成会话

深度整合需要:

“能够通过调度操作进行导航”

然而,他们推荐这种方法作为“深度集成”的替代方案:

“你可以将提供给路由组件的历史对象传递给你的操作,而不是分派操作来导航。”

所以你可以用withRouter高阶组件来包装你的组件:

export default withthrouter (connect(null, {actionCreatorName})(ReactComponent));

它将历史API传递给道具。你可以调用动作创建者传递历史作为参数。例如,在你的ReactComponent中:

onClick={() => {
  this.props.actionCreatorName(
    this.props.history,
    otherParams
  );
}}

然后,在actions/index.js中:

export function actionCreatorName(history, param) {
  return dispatch => {
    dispatch({
      type: SOME_ACTION,
      payload: param.data
    });
    history.push("/path");
  };
}

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

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为空以匹配路径。

在这种情况下,你将道具传递给你的坦克。所以你可以简单地打电话

props.history.push('/cart')

如果情况并非如此,您仍然可以从组件传递历史记录

export function addProduct(data, history) {
  return dispatch => {
    axios.post('/url', data).then((response) => {
      dispatch({ type: types.AUTH_USER })
      history.push('/cart')
    })
  }
}

This.context.history.push将不起作用。

我设法让推工作如下:

static contextTypes = {
    router: PropTypes.object
}

handleSubmit(e) {
    e.preventDefault();

    if (this.props.auth.success) {
        this.context.router.history.push("/some/Path")
    }

}