我有一个使用react @0.14、redux @3.05、react-router @1.0.3 和 redux-simple-router @2.0.2 的应用程序。我正在尝试根据商店状态为我的一些路线配置 onEnter 转换。转换挂钩成功触发并将新状态推送到我的商店,这会更改 url。但是,页面上呈现的实际组件是来自路由匹配的原始组件处理程序,而不是新 url 的新组件处理程序。
这是我的routes.js
文件看起来像
export default function configRoutes(store) {
const authTransition = function authTransition(location, replaceWith) {
const state = store.getState()
const user = state.user
if (!user.isAuthenticated) {
store.dispatch(routeActions.push('/login'))
}
}
return (
<Route component={App}>
<Route path="/" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/dashboard" component={Dashboard} onEnter={authTransition}/>
<Route path="/workouts" component={Workout} onEnter={authTransition}>
<IndexRoute component={WorkoutsView}/>
<Route path="/workouts/create" component={WorkoutCreate}/>
</Route>
</Route>
)
}
这是我的Root.js
插入到 DOM 中的组件
export default class Root extends React.Component {
render() {
const { store, history } = this.props
const routes = configRoutes(store)
return (
<Provider store={store}>
<div>
{isDev ? <DevTools /> : null}
<Router history={history} children={routes} />
</div>
</Provider>
)
}
}
澄清一下,如果我转到“/workouts”,它将触发 onEnter authTransition 挂钩,调度 redux-simple-router 推送操作,将 url 更改为“/login”,但会在页面上显示 Workout 组件。查看 Redux DevTools 表明state -> router -> location -> pathname
是“/登录”。
状态流为
- @@INIT
- @@ROUTER/UPDATE_LOCATION(/锻炼)
- @@ROUTER/UPDATE_LOCATION(/登录)
我是否错误地通过商店到达路线?我不明白为什么下一个 Router/Update_Location 不起作用
结果你想使用react-router api(替换),而不是redux-simple-router来控制你的转换。
const authTransition = function authTransition(nextState, replace, callback) {
const state = store.getState()
const user = state.user
// todo: in react-router 2.0, you can pass a single object to replace :)
if (!user.isAuthenticated) {
replace({ nextPathname: nextState.location.pathname }, '/login', nextState.location.query)
}
callback()
}
另外,要小心。我看到了很多有关反应路由器替换传递单个对象的文档。这是针对 React-router 2.0-rc* 的。如果您使用的是react-router 1.0,您将需要传递replace 3个单独的参数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)