gpt4 book ai didi

javascript - React-Router-Redux 分派(dispatch) LOCATION_CHANGE 两次,删除搜索值

转载 作者:行者123 更新时间:2023-11-30 21:10:36 25 4
gpt4 key购买 nike

我正在使用与 react-router 4.x 兼容的下一个 (5.0.0-alpha.6) 版本 react-router-redux。我尝试在重定向到下一页时在 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}`}))
}
}
//....

最佳答案

我认为你应该在 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}`}))
}
}

//...

关于javascript - React-Router-Redux 分派(dispatch) LOCATION_CHANGE 两次,删除搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com