React-Router-Redux两次调度LOCATION_CHANGE,删除搜索值

时间:2017-09-12 16:12:35

标签: javascript reactjs redux react-redux react-router-redux

我正在使用下一个(5.0.0-alpha.6)版本react-router-redux,它与react-router 4.x兼容。 我尝试在重定向到下一页时在url上设置参数。

每次移动到下一页。我意识到它打电话给@LOCATION_CHANGE 2次,in the second time it removes search value。如果我从按钮事件

处理它,它工作正常
import { requireAuth } from '../components/AuthenticatedComponent'
import createHistory from 'history/createBrowserHistory'

const history = createHistory()  

return (
    <ConnectedRouter history={history}>
      <div className="container">
        <Header />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={requireAuth(About)} />
          <Route path="/login" component={Login} />
          <Route component={NotFound} />
        </Switch>
      </div>
    </ConnectedRouter>
  )

AuthenticatedComponent.js

import { push } from 'react-router-redux'

export function requireAuth(Component) {

class AuthenticatedComponent extends React.Component {

    componentWillMount() {
        this.checkAuth(this.props.isAuthenticated);
    }

    componentWillReceiveProps(nextProps) {
        this.checkAuth(nextProps.isAuthenticated);
    }

    checkAuth(isAuthenticated) {
        if (!isAuthenticated) {
            let redirectAfterLogin = this.props.location.pathname;
            this.props.dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`}))
        }
    }
 //....

}

3 个答案:

答案 0 :(得分:1)

我认为你应该在nextProps中传递路径名。

class AuthenticatedComponent extends React.Component {

//...

componentWillReceiveProps(nextProps) {
    this.checkAuth(nextProps.isAuthenticated); // <--- call checkAuth
}

checkAuth(isAuthenticated) {
    if (!isAuthenticated) { // <-- isAuthenticated is in nextProps

        // this.props.location.pathame is not in nextProps
        let redirectAfterLogin = this.props.location.pathname;
        this.props.dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`}))
    }
 }

//...
class AuthenticatedComponent extends React.Component {

componentWillMount() {
    this.checkAuth(this.props);
}

componentWillReceiveProps(nextProps) {
    this.checkAuth(nextProps); // <--- call checkAuth
}

checkAuth({isAuthenticated, location, dispatch}) {
    if (!isAuthenticated) { 
        let redirectAfterLogin = location.pathname;
        dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`}))
    }
 }

//...

答案 1 :(得分:0)

react-router-redux已不再维护。对于您的Redux <->路由器,需要与React Router 4+同步。让我们使用connected-react-route r库来解决此问题。

答案 2 :(得分:0)

以防万一有人遇到类似问题,我正在使用connected-react-router库,而push则引发了双重LOCATION_CHANGE事件。第一个事件将具有正确的搜索参数,而第二个事件将清除它。我的问题是我正在从Link中将按钮渲染为react-router-dom

<Button
  as={Link}
  basic
  className={styles.basicTealButton}
  onClick={this.handleButtonClick}
>
...

一旦我摆脱了as={Link}部分,一切就很好了。