Javascript 基于前面的路径url对componentWillReceiveProps调用方法
我试图实现的是基于前面路径url的方法调用(我使用的是react路由器) 前面的路径URL看起来像Javascript 基于前面的路径url对componentWillReceiveProps调用方法,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我试图实现的是基于前面路径url的方法调用(我使用的是react路由器) 前面的路径URL看起来像 import React, { PropTypes, Component } from "react"; import MyComponentView from "./view"; class MyComponent extends Component { componentWillReceiveProps(nextProps) { if ( // prevoius pa
import React, { PropTypes, Component } from "react";
import MyComponentView from "./view";
class MyComponent extends Component {
componentWillReceiveProps(nextProps) {
if ( // prevoius path logic check ) {
this.props.myMethod(); // Calling the method over here
}
}
render() {
return (
<MyComponentView {...this.props} />
);
}
}
export default MyComponent;
http://www.website.com/signin?f=world-news&join=true&nextPath=%2Ff%2Fworld news
成功登录后,用户将被重定向到
http://www.website.com/f/world-news
现在,当我的组件被挂载并看到新的URL时,我想触发一个方法,但前提是用户是从我在问题中指定的前一个URL登录的。上一个URL中的唯一字符串是&join=true
。当前面的路径包含&join=true
示例伪代码如下所示
import React, { PropTypes, Component } from "react";
import MyComponentView from "./view";
class MyComponent extends Component {
componentWillReceiveProps(nextProps) {
if ( // prevoius path logic check ) {
this.props.myMethod(); // Calling the method over here
}
}
render() {
return (
<MyComponentView {...this.props} />
);
}
}
export default MyComponent;
总之,当我单击组件中的按钮时,它会检查用户是否登录。如果用户已登录,我将调用原始代码示例中提到的方法myMethod()
如果没有,我会将用户重定向到登录页面(调用transitionosignandautojoin
),该页面采用当前路径并重定向到登录路径。例如,如果我的当前路径名为http://www.website.com/f/world-news
如果用户未登录,则新的重定向url看起来像http://www.website.com/signin?f=world-news&join=true&nextPath=%2Ff%2Fworld news
成功登录后,用户将重定向回
http://www.website.com/f/world-news
,但现在我想在安装组件时自动调用myMethod()
。但是,只有当上一个url包含&join=true
时,才应自动调用myMethod()
,而不是依赖上一个url,您可以在重定向时将状态
对象添加到
function redirectAfterSignin() {
const {
nextPath,
join = false
} = this.props.location.query
this.router.push({
pathname: nextPath,
state: { join }
})
}
然后在另一个组件中,您只需要检查位置。state
prop来确定join
值
class MyComponent extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.location.state.join) {
// do something
}
}
}
您是否使用任何类型的flux或本地数据存储解决方案?我没有使用本地数据存储。当涉及到通量时,我使用redux如果重定向是使用
react router
完成的,那么您应该能够在reducer中存储以前的路径。您是否正在使用react router
进行此重定向?@HussienK我已添加了重定向代码,并添加了其他信息,说明我试图实现的目标。您在Redux操作中的重定向功能是什么?因为您可以通过发送一个操作来保存上一个url。我应该在哪里定义并调用redirectAfterSignin
?无论您当前从哪里重定向到nextPath
,您都应该使用该函数中的代码。