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


当前回答

如果你想在将一个函数作为一个值传递给组件的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中)

其他回答

这是我的hack(这是我的根级文件,其中混合了一些redux -尽管我没有使用react-router-redux):

const store = configureStore()
const customHistory = createBrowserHistory({
  basename: config.urlBasename || ''
})

ReactDOM.render(
  <Provider store={store}>
    <Router history={customHistory}>
      <Route component={({history}) => {
        window.appHistory = history
        return (
          <App />
        )
      }}/>
    </Router>
  </Provider>,
  document.getElementById('root')
)

然后,我可以在任何我想要的地方使用window.appHistory.push()(例如,在我的redux商店函数/ thacks /sagas等),我希望我可以只使用window.customHistory.push(),但出于某种原因,react-router似乎从未更新,即使url发生了变化。但是这样我就有了react-router使用的EXACT实例。我不喜欢把东西放在全球范围内,这是我做过的为数不多的事情之一。但在我看来,这比我见过的任何其他选择都要好。

这个棘手的问题,花了我很多时间,但最终,我是这样解决的:

用withRouter包装容器,并将历史记录传递给mapDispatchToProps函数中的动作。实际操作中使用history.push('/url')进行导航。

行动:

export function saveData(history, data) {
  fetch.post('/save', data)
     .then((response) => {
       ...
       history.push('/url');
     })
};

容器:

import { withRouter } from 'react-router-dom';
...
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    save: (data) => dispatch(saveData(ownProps.history, data))}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));

这对React Router v4.x有效。

React路由器V4现在允许历史道具如下所示:

this.props.history.push("/dummy",value)

然后,只要位置道具可用,就可以访问该值 State:{value}不是组件状态。

根据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");
  };
}

所以我的做法是: -而不是使用历史重定向。推送,我只是使用从react-router-dom重定向组件 当使用这个组件时,你只需要传递push=true,它就会处理剩下的事情

import * as React from 'react';
import { Redirect } from 'react-router-dom';
class Example extends React.Component {
  componentDidMount() {
    this.setState({
      redirectTo: '/test/path'
    });
  }

  render() {
    const { redirectTo } = this.state;

    return <Redirect to={{pathname: redirectTo}} push={true}/>
  }
}