我想实现的是调用基于前一个路径url(我正在使用react-router)的方法。根据以前的路径URL在componentWillReceiveProps上调用方法
之前的路径URL看起来像
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
。我如何可以调用的方法在componentWillReceiveProps
当先前的路径包含&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;
更新:添加代码重定向功能
_getCurrentPathName() {
let path = window.location.pathname + window.location.search;
if (path === "/") {
return undefined;
}
return path;
}
transitionToSigninAndAutoJoin(query) {
const q = Object.assign({}, query, {
f: this.props.params.slug,
nextPath: this._getCurrentPathName(),
join: true
});
this.transitionTo({ pathname: "/signin", query: q });
}
总之,当我点击我的组件中的一个按钮,它会检查用户是否已登录。如果用户已登录,我正在调用原始代码示例中提到的方法myMethod()
。
如果不是,我将用户重定向到登录页面(呼叫transitionToSigninAndAutoJoin
),该页面采用当前路径并重定向到登录路径。对于例如如果我当前的路径名http://www.website.com/f/world-news
和用户没有登录,新重定向的URL看起来像http://www.website.com/signin?f=world-news&join=true&nextPath=%2Ff%2Fworld-news
在SUCESSFUL登入用户被重定向回http://www.website.com/f/world-news
,但现在我想自动调用myMethod()
组件时mountedd。然而,myMethod()
只应自动当以前的URL中包含&join=true
您是否在使用任何助焊剂或本地数据存储解决方案? – HussienK
我没有使用本地数据存储。当它使用flux时,我正在使用redux – zaq
如果重定向是使用react-router完成的,那么您应该能够将以前的路径存储在reducer中。你是否在使用'react-router'做这个重定向? – HussienK