umi#history JavaScript Examples
The following examples show how to use
umi#history.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: 404.jsx From vpp with MIT License | 6 votes |
NoFoundPage = () => (
<Result
status="404"
title="404"
subTitle="Sorry, the page you visited does not exist."
extra={
<Button type="primary" onClick={() => history.push('/')}>
Back Home
</Button>
}
/>
)
Example #2
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
// replace url without redirecting, https://stackoverflow.com/a/3503206/10566022
window.history.replaceState("", "", urlWithNewChain)
Example #3
Source File: BasicLayout.jsx From vpp with MIT License | 5 votes |
BasicLayout = props => {
const {
dispatch,
children,
settings,
location = {
pathname: '/',
},
} = props;
/**
* constructor
*/
useEffect(() => {
if (dispatch) {
dispatch({
type: 'user/fetchCurrent',
});
}
}, []);
/**
* init variables
*/
const handleMenuCollapse = payload => {
if (dispatch) {
dispatch({
type: 'global/changeLayoutCollapsed',
payload,
});
}
}; // get children authority
const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
authority: undefined,
};
const { formatMessage } = useIntl();
return (
<ProLayout
logo={logo}
formatMessage={formatMessage}
onCollapse={handleMenuCollapse}
onMenuHeaderClick={() => history.push('/')}
menuItemRender={(menuItemProps, defaultDom) => {
if (menuItemProps.isUrl || !menuItemProps.path) {
return defaultDom;
}
return <Link to={menuItemProps.path}>{defaultDom}</Link>;
}}
breadcrumbRender={(routers = []) => [
{
path: '/',
breadcrumbName: formatMessage({
id: 'menu.home',
}),
},
...routers,
]}
itemRender={(route, params, routes, paths) => {
const first = routes.indexOf(route) === 0;
return first ? (
<Link to={paths.join('/')}>{route.breadcrumbName}</Link>
) : (
<span>{route.breadcrumbName}</span>
);
}}
footerRender={() => defaultFooterDom}
menuDataRender={menuDataRender}
rightContentRender={() => <RightContent />}
{...props}
{...settings}
>
<Authorized authority={authorized.authority} noMatch={noMatch}>
{children}
</Authorized>
</ProLayout>
);
}
Example #4
Source File: login.js From vpp with MIT License | 5 votes |
Model = {
namespace: 'login',
state: {
status: undefined,
},
effects: {
*login({ payload }, { call, put }) {
const response = yield call(fakeAccountLogin, payload);
yield put({
type: 'changeLoginStatus',
payload: response,
}); // Login successfully
if (response.status === 'ok') {
const urlParams = new URL(window.location.href);
const params = getPageQuery();
let { redirect } = params;
if (redirect) {
const redirectUrlParams = new URL(redirect);
if (redirectUrlParams.origin === urlParams.origin) {
redirect = redirect.substr(urlParams.origin.length);
if (redirect.match(/^\/.*#/)) {
redirect = redirect.substr(redirect.indexOf('#') + 1);
}
} else {
window.location.href = '/';
return;
}
}
history.replace(redirect || '/');
}
},
logout() {
const { redirect } = getPageQuery(); // Note: There may be security issues, please note
if (window.location.pathname !== '/user/login' && !redirect) {
history.replace({
pathname: '/user/login',
search: stringify({
redirect: window.location.href,
}),
});
}
},
},
reducers: {
changeLoginStatus(state, { payload }) {
setAuthority(payload.currentAuthority);
return { ...state, status: payload.status, type: payload.type };
},
},
}
Example #5
Source File: index.js From acy-dex-interface with MIT License | 4 votes |
useConstantLoader = () => {
const { account, chainId, library } = useWeb3React();
const [constant, setConstant] = useState(constantInstance);
const marketChainId = Number(localStorage.getItem("market"));
useEffect(() => {
const chainSupportedIndex = (supportedChainIds.indexOf(chainId) !== -1);
const fallbackChainId = chainSupportedIndex ? chainId : initialChainId; // redirect unsupported chainId and undefined to 56
console.log("chainId before fallback:", chainId);
console.log("fallbackChainId chainId:", fallbackChainId);
const marketChainSupportedIndex = (supportedChainIds.indexOf(marketChainId) !== -1);
const marketNetwork = marketChainSupportedIndex ? marketChainId : 56;
const staticConstants = ConstantLoader(fallbackChainId, marketNetwork);
const constants = Object.assign({
'account': chainSupportedIndex ? account : undefined,
'chainId': fallbackChainId,
'library': chainSupportedIndex ? library : defaultLibrary,
'marketNetwork': marketNetwork,
}, staticConstants);
constantInstance = constants;
setConstant(constants);
}, [account, chainId, marketChainId]);
// 将实际的 chainId 显示在 url 的参数里
const changeUrlChainId = (nextChainId) => {
const chainName = chainId2UrlChainName(nextChainId);
if (history.location.query.chain !== chainName) {
// history.replace({
// pathname: history.location.pathname,
// query: {
// chain: chainName,
// },
// })
function replaceUrlParam(url, paramName, paramValue) {
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b(' + paramName + '=).*?(&|#|$)');
if (url.search(pattern) >= 0) {
return url.replace(pattern, '$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/, '');
return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
}
const urlWithNewChain = replaceUrlParam(window.location.href, "chain", chainName);
// window.location.replace(urlWithNewChain);
// window.location.reload();
console.log("redirected")
}
}
// 请求切换 chain network
const switchChain = async (givenChainId) => {
if (localStorage.getItem("wallet") === "metamask") {
try {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: givenChainId }],
});
} catch (e) {
if (e.code === 4902) {
try {
await ethereum.request({
method: 'wallet_addEthereumChain',
params: [
networkParams[givenChainId]
],
});
} catch (addError) {
console.error(addError);
}
} else {
// 失败时,将 url 的 chainId 切换回原本的
changeUrlChainId();
}
}
}
else if (localStorage.getItem("wallet") === "nabox") {
try {
await NaboxWallet.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: givenChainId }],
});
} catch (e) {
if (e.code === 4902) {
try {
await NaboxWallet.request({
method: 'wallet_addEthereumChain',
params: [
networkParams[givenChainId]
],
});
} catch (addError) {
console.error(addError);
}
} else {
// 失败时,将 url 的 chainId 切换回原本的
changeUrlChainId();
}
}
}
else if (localStorage.getItem("wallet") === "binance") {
try {
await BinanceChain.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: givenChainId }],
});
} catch (e) {
if (e.code === 4902) {
try {
await BinanceChain.request({
method: 'wallet_addEthereumChain',
params: [
networkParams[givenChainId]
],
});
} catch (addError) {
console.error(addError);
}
} else {
// 失败时,将 url 的 chainId 切换回原本的
changeUrlChainId();
}
}
}
}
// // chainId 有更动时,url 显示的 chainId 也应该修改
// useEffect(() => {
// // debugger;
// changeUrlChainId()
// // console.log("current chainId: " , history.location);
// }, [chainId])
useEffect(() => {
if (window.ethereum) {
ethereum.on("chainChanged", (_chainId) => {
const nextChainId = parseInt(_chainId);
console.log("initialChainId changed to ", nextChainId);
localStorage.setItem("initialChainId", nextChainId);
window.location.reload()
// changeUrlChainId(nextChainId)
})
}
}, [])
// // 如果手动修改 url 的 chainId,就触发切换 chain network 的请求
// // @TODO: 用户还没 connect 钱包时不要触发 request
// useEffect(() => {
// if ("chain" in history.location.query) {
// const urlChainName = history.location.query.chain;
// const urlChainId = urlChainName2ChainId(urlChainName);
// // localStorage.setItem("initialChainId", urlChainId);
// if (urlChainId !== -1 && urlChainId !== chainId) {
// // console.log("switch to chainId:", urlChainId);
// switchChain("0x".concat(urlChainId.toString(16)));
// }
// }
// }, [history.location.query])
return constant;
}
Example #6
Source File: Sidebar.js From acy-dex-interface with MIT License | 4 votes |
Sidebar = (props) => {
// state = {
// visible: true,
// };
const [selectedTab, setSelectedTab] = useState(1);
// static getDerivedStateFromProps(props, state) {
// if (!props.autoHideHeader && !state.visible) {
// return {
// visible: true,
// };
// }
// return null;
// }
// getHeadWidth = () => {
// const { isMobile, collapsed, setting } = this.props;
// const { fixedHeader, layout } = setting;
// if (isMobile || !fixedHeader || layout === 'topmenu') {
// return '100%';
// }
// return collapsed ? 'calc(100% - 80px)' : 'calc(100% - 256px)';
// };
// handleNoticeClear = type => {
// message.success(
// `${formatMessage({ id: 'component.noticeIcon.cleared' })} ${formatMessage({
// id: `component.globalHeader.${type}`,
// })}`
// );
// const { dispatch } = this.props;
// dispatch({
// type: 'global/clearNotices',
// payload: type,
// });
// };
const handleMenuClick = (e) => {
console.log(e.key);
// const { dispatch } = props;
if (e.key === 'launch') {
history.push('/launchpad');
}
if (e.key === 'exchange') {
history.push('/exchange')
}
// if (key === 'triggerError') {
// history.push('/exception/trigger');
// return;
// }
// if (key === 'userinfo') {
// history.push('/account/settings/base');
// // return;
// }
// // if (key === 'logout') {
// // dispatch({
// // type: 'login/logout',
// // });
// // }
};
// handScroll = () => {
// const { autoHideHeader } = this.props;
// const { visible } = this.state;
// if (!autoHideHeader) {
// return;
// }
// const scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
// if (!this.ticking) {
// this.ticking = true;
// requestAnimationFrame(() => {
// if (this.oldScrollTop > scrollTop) {
// this.setState({
// visible: true,
// });
// } else if (scrollTop > 300 && visible) {
// this.setState({
// visible: false,
// });
// } else if (scrollTop < 300 && !visible) {
// this.setState({
// visible: true,
// });
// }
// this.oldScrollTop = scrollTop;
// this.ticking = false;
// });
// }
// };
// const { isMobile, handleMenuCollapse, setting } = this.props;
// const { navTheme, layout, fixedHeader } = setting;
// const { visible } = this.state;
// const isTop = layout === 'topmenu';
// const width = this.getHeadWidth();
// const HeaderDom = visible ? (
// <Header style={{ padding: 0, width }} className={fixedHeader ? styles.fixedHeader : ''}>
// <TopNavHeader
// theme={navTheme}
// mode="horizontal"
// onCollapse={handleMenuCollapse}
// onNoticeClear={this.handleNoticeClear}
// onMenuClick={this.handleMenuClick}
// onNoticeVisibleChange={this.handleNoticeVisibleChange}
// {...this.props}
// />
// </Header>
// ) : null;
const tabMenu = selectedTab === 1 ?
(
<Menu
theme='dark'
onClick={handleMenuClick}
mode="inline"
defaultSelectedKeys={['1']}
defaultOpenKeys={['sub1']}
style={{ height: '100%' }}
>
<SubMenu
key="sub1"
title={
<span>
<Icon type='mail' />
<span> subnav1</span>
</span>}
>
<Menu.Item key="1">Market</Menu.Item>
<Menu.Item key="2">Perpetual</Menu.Item>
<Menu.Item key="3">Stats</Menu.Item>
<Menu.Item key="exchange">
<Icon type='money-collect' />
Exchange
</Menu.Item>
</SubMenu>
<SubMenu key="sub2" icon={<LaptopOutlined />} title="subnav 2">
<Icon type="LaptopOutlined" />
<Menu.Item key="5">
<Icon type="mail" />
Liquidity
</Menu.Item>
<Menu.Item key="6">Farm</Menu.Item>
<Menu.Item key="launch">
<Icon type="rocket" />
Launch
</Menu.Item>
</SubMenu>
<Menu.Item key="mail">
<Icon type="mail" />
navButton
</Menu.Item>
</Menu>
) :
(
<Menu
theme='dark'
onClick={handleMenuClick}
mode="inline"
defaultSelectedKeys={['1']}
defaultOpenKeys={['sub1']}
style={{ height: '100%' }}
>
<SubMenu
key="sub1"
title={
<span>
<Icon type='mail' />
<span> subnav1</span>
</span>}
>
<Menu.Item key="1">Market</Menu.Item>
<Menu.Item key="exchange">
<Icon type='money-collect' />
Exchange
</Menu.Item>
</SubMenu>
</Menu>
);
return (
<Sider
theme='dark'
style={{
overflow: 'auto',
height: '100%',
position: 'fixed',
left: 0,
top: 0,
bottom: 0,
}}
>
<div className="ant-btn-group" style={{marginLeft: "10px", marginTop: "60px", marginBottom: "10px"}}>
<Button type="primary" icon="download" onClick={() => setSelectedTab(1)} ghost={selectedTab === 2}> Tab1 </Button>
<Button type="primary" icon="mail" onClick={() => setSelectedTab(2)} ghost={selectedTab === 1}> Tab2 </Button>
</div>
{tabMenu}
</Sider>
);
}
Example #7
Source File: request.js From acy-dex-interface with MIT License | 4 votes |
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [option] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, option) {
const options = {
expirys: isAntdPro(),
...option,
};
/**
* Produce fingerprints based on url and parameters
* Maybe url has the same parameters
*/
const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
const hashcode = hash
.sha256()
.update(fingerprint)
.digest('hex');
const defaultOptions = {
credentials: 'include',
};
const newOptions = { ...defaultOptions, ...options };
if (
newOptions.method === 'POST' ||
newOptions.method === 'PUT' ||
newOptions.method === 'DELETE'
) {
if (!(newOptions.body instanceof FormData)) {
newOptions.headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
...newOptions.headers,
};
newOptions.body = JSON.stringify(newOptions.body);
} else {
// newOptions.body is FormData
newOptions.headers = {
Accept: 'application/json',
...newOptions.headers,
};
}
}
const expirys = options.expirys && 60;
// options.expirys !== false, return the cache,
if (options.expirys !== false) {
const cached = sessionStorage.getItem(hashcode);
const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
if (cached !== null && whenCached !== null) {
const age = (Date.now() - whenCached) / 1000;
if (age < expirys) {
const response = new Response(new Blob([cached]));
return response.json();
}
sessionStorage.removeItem(hashcode);
sessionStorage.removeItem(`${hashcode}:timestamp`);
}
}
return fetch(url, newOptions)
.then(checkStatus)
.then(response => cachedSave(response, hashcode))
.then(response => {
// DELETE and 204 do not return data by default
// using .json will report an error.
if (newOptions.method === 'DELETE' || response.status === 204) {
return response.text();
}
return response.json();
})
.catch(e => {
const status = e.name;
if (status === 401) {
// @HACK
/* eslint-disable no-underscore-dangle */
window.g_app._store.dispatch({
type: 'login/logout',
});
return;
}
// environment should not be used
if (status === 403) {
history.push('/exception/403');
return;
}
if (status <= 504 && status >= 500) {
history.push('/exception/500');
return;
}
if (status >= 404 && status < 422) {
history.push('/exception/404');
}
});
}
Example #8
Source File: BasicLayout.jsx From the-eye-knows-the-garbage with MIT License | 4 votes |
BasicLayout = props => {
const [menuData, setMenuData] = useState([]);
const {
dispatch,
children,
settings,
location = {
pathname: '/',
},
} = props;
/**
* constructor
*/
useEffect(() => {
if (dispatch) {
dispatch({
type: 'user/fetchCurrent',
});
}
}, []);
useEffect(() => {
queryMenu().then(data => {
let menuData = data.data
menuData.map((item)=>{
item.icon = <DynamicIcon type={item.icon} />
})
setMenuData(menuData || []);
});
}, []);
/**
* init variables
*/
const handleMenuCollapse = payload => {
if (dispatch) {
dispatch({
type: 'global/changeLayoutCollapsed',
payload,
});
}
}; // get children authority
const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
authority: undefined,
};
console.log("authorized")
console.log(authorized)
const { formatMessage } = useIntl();
return (
<ProLayout
logo={logo}
formatMessage={formatMessage}
onCollapse={handleMenuCollapse}
onMenuHeaderClick={() => history.push('/xadmin')}
menuItemRender={(menuItemProps, defaultDom) => {
if (menuItemProps.isUrl || !menuItemProps.path) {
return defaultDom;
}
return <Link to={menuItemProps.path}>{defaultDom}</Link>;
}}
breadcrumbRender={(routers = []) => [
{
path: '/',
breadcrumbName: formatMessage({
id: 'menu.home',
}),
},
...routers,
]}
itemRender={(route, params, routes, paths) => {
const first = routes.indexOf(route) === 0;
return first ? (
// <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
<Link to={'/xadmin'}>{route.breadcrumbName}</Link>
) : (
<span>{route.breadcrumbName}</span>
);
}}
footerRender={() => defaultFooterDom}
// menuDataRender={menuDataRender}
menuDataRender={() =>menuData}
rightContentRender={() => <RightContent />}
{...props}
{...settings}
>
<Authorized authority={authorized.authority} noMatch={noMatch}>
{children}
</Authorized>
</ProLayout>
);
}
Example #9
Source File: login.js From the-eye-knows-the-garbage with MIT License | 4 votes |
Model = {
namespace: 'login',
state: {
status: undefined,
errors: {},
},
effects: {
* login({payload}, {call, put}) {
yield put({
type: 'clearErrors',
});
try {
const response = yield call(AccountLogin, payload);
yield put({
type: 'changeLoginStatus',
payload: response,
}); // Login successfully
if (response.status === 'ok') {
const urlParams = new URL(window.location.href);
const params = getPageQuery();
let {redirect} = params;
if (redirect) {
const redirectUrlParams = new URL(redirect);
if (redirectUrlParams.origin === urlParams.origin) {
redirect = redirect.substr(urlParams.origin.length);
if (redirect.match(/^\/.*#/)) {
redirect = redirect.substr(redirect.indexOf('#') + 1);
}
} else {
window.location.href = '/';
return;
}
}
history.replace(redirect || '/xadmin');
}
return response
}catch (error){
console.log(error)
console.log("error in login")
return error
}
},
* email({email}, {call, put}) {
try {
yield put({
type: 'clearErrors',
});
const res = yield call(getEmailCaptcha, email);
if (res) {
return res;
}
} catch (errors) {
yield put({
type: 'errorsHandle',
payload: errors.data.fields_errors,
});
}
},
logout() {
Logout().then(r =>
message.success('成功退出登录'),
);
reloadAuthorized();
localStorage.clear();
const {redirect} = getPageQuery(); // Note: There may be security issues, please note
if (window.location.pathname !== '/xadmin/login' && !redirect) {
history.replace({
pathname: '/xadmin/login',
search: stringify({
redirect: window.location.href,
}),
});
}
},
},
reducers: {
errorsHandle(state, {payload}) {
return {
...state,
errors: payload,
};
},
clearErrors(state, {}) {
return {
...state,
errors: {},
};
},
changeLoginStatus(state, {payload}) {
setAuthority(payload.currentAuthority);
return {...state, status: payload.status, type: payload.type};
},
},
}
Example #10
Source File: index.jsx From the-eye-knows-the-garbage with MIT License | 4 votes |
ChangePassPage = () => {
const [form] = Form.useForm();
const handleChange = (values) => {
changePassword(values).then(
(r) => {
message.success('密码修改成功,请重新登录!');
if (window.location.pathname !== '/xadmin/login') {
history.replace({
pathname: '/xadmin/login',
});
}
},
).catch((error) => {
if ('fields_errors' in error.data) {
for (let key in error.data.fields_errors) {
var value = error.data.fields_errors[key];
form.setFields([
{
name: key,
errors: value,
},
]);
}
} else {
message.error('非字段类型错误');
}
});
};
return (
<PageHeaderWrapper>
<Card title={'修改当前账号密码'}>
<Form
form={form}
onFinish={handleChange}
>
<FormItem
labelCol={{
span: 5,
}}
wrapperCol={{
span: 10,
}}
label="旧密码"
name="old_password"
rules={[
{
required: true,
message: '请输入旧密码!',
},
]}
>
<Input.Password placeholder="请输入旧密码" type="password" />
</FormItem>
<FormItem
labelCol={{
span: 5,
}}
wrapperCol={{
span: 10,
}}
label="新密码"
name="new_password"
rules={[
{
required: true,
message: '请输入新密码!',
},
]}
>
<Input.Password placeholder="请输入新密码" type="password" />
</FormItem>
<FormItem
labelCol={{
span: 5,
}}
wrapperCol={{
span: 10,
}}
label="重复新密码"
name="re_password"
rules={[
{
required: true,
message: '请再次输入新密码',
},
({ getFieldValue }) => ({
validator(rule, value) {
if (!value || getFieldValue('new_password') === value) {
return Promise.resolve();
}
return Promise.reject('两次密码不匹配');
},
}),
]}
>
<Input.Password placeholder="请再次输入新密码" type="password" />
</FormItem>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
修改
</Button>
</Form.Item>
</Form>
</Card>
</PageHeaderWrapper>
);
}