相关疑难解决方法(0)

如何使用react-router防止路由更改

我的React应用程序中有一个页面,如果表单很脏,我想阻止用户离开.

在我的react-routes中,我正在使用onLeave prop这样:

<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>
Run Code Online (Sandbox Code Playgroud)

而我的onLeave是:

const checkForm = (nextState, replace, cb) => {
  if (form.IsDirty) {
    console.log('Leaving so soon?');
    // I would like to stay on the same page somehow...
  }
};
Run Code Online (Sandbox Code Playgroud)

有没有办法防止新路由被触发并使用户保持在同一页面上?

reactjs react-router

16
推荐指数
3
解决办法
2万
查看次数

React-router-dom v6 useHistory location.pathname

由于react-router-domuseHistory不再受支持,我正在寻找一个等效的使用history.location.pathname

reactjs react-router-dom

9
推荐指数
1
解决办法
4870
查看次数

react-router withRouter不提供mapStateToProps中的道具?

我目前正面临一个奇怪的问题,即withRouter提供的HOC react-router没有将道具传递给mapStateToProps函数.我在这做错了吗?

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import { connect } from 'react-redux';


class ThisClass extends Component {
    render() {
        console.log(this.props.router); // Returns object with router keys (params, router, go, routes, ...)
        // Render stuff
    }
}

const mapStateToProps = (state, props) => {
    console.log(state); // returns state of redux
    console.log(props); // returns empty object -> {}, how come this is empty?!

    return {
        consultations: patientThisClassSelector(state, props)
    }; …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router

7
推荐指数
1
解决办法
2237
查看次数

React Router 6 - useLocation 没有像我预期的那样工作

我是 React 新手,所以我确信我不理解 useLocation 的用例 - 比如它有什么用处和它不适合什么。

我想要一种方法,使特定组件可以知道任何位置更改,包括来自 PushState 的位置更改。注意:我正在转换 Anuglar JS 1.0 代码库,该代码库仅使用哈希中的所有查询信息。我想在此重写中使用 PushState 浏览器功能。

下面的示例代码(我只是将其作为新的 React 应用程序组件中的单个组件:

import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const RandLocation: React.FC = () => {
    const location = useLocation();

    useEffect(() => {
        console.log('location: ', location);
    }, [location]);
    
    return (
        <div>
            <button 
            onClick={() => {const r =  Math.random(); window.history.pushState({'rnd': r }, '', '/?rnd=' + r)}}>
                Click Me</button>
            <br/>
        </div>
    )
}
export default RandLocation;
Run Code Online (Sandbox Code Playgroud)

我只看到 useEffect 在加载时运行,以及使用浏览器按钮前进或后退。但当我点击“Click …

javascript pushstate typescript reactjs react-router-dom

1
推荐指数
1
解决办法
2835
查看次数