gpt4 book ai didi

reactjs - 在react-router 2.4.0中重定向willTransitionTo?

转载 作者:行者123 更新时间:2023-12-03 13:37:48 25 4
gpt4 key购买 nike

我目前在我的聊天应用程序上使用 "react-router": "^2.4.0" ,并且对没有用户时如何重定向感到困惑。我认为 redirect"^2.4.0" 中不起作用。

我应该在我的聊天路径上使用onEnter Hook 吗?

类似这样的事情:

 <Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>

routes.js

 <Route path="/" component={App} >
<IndexRoute component={Chat} />
<Route path="chat" component={Chat} />
<Route path="login" component={Login} />
</Route>

Chat.jsx

static willTransitionTo(transition){
var state = ChatStore.getState();
if(!state.user){
transition.redirect('/login');
}
}

最佳答案

我通过使用 setRouteLeaveHook 使其工作,如下所示: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

return false to prevent a transition w/o prompting the user

但是,他们忘记提及该钩子(Hook)也应该取消注册,请参阅 herehere .

我们可以使用它来实现我们自己的解决方案,如下所示:

class YourComponent extends Component {
constructor() {
super();

const {route} = this.props;
const {router} = this.context;

this.unregisterLeaveHook = router.setRouteLeaveHook(
route,
this.routerWillLeave.bind(this)
);
}

componentWillUnmount() {
this.unregisterLeaveHook();
}

routerWillLeave() {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
if (!this.state.isSaved) {
return 'Your work is not saved! Are you sure you want to leave?'
}
}
...
}

YourComponent.contextTypes = {
router: routerShape
};

关于reactjs - 在react-router 2.4.0中重定向willTransitionTo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36975803/

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