当某个页面没有被Route包裹时props中是没有history的
此时可以用到类似useHistory的属性
该属性使用时只能加载到组件中使用,无法写到全局中
如果使用中报错可以尝试把react-router-dom的版本重新下载成5.1.2版本
也可以使用createHashHistory
其他属性用法都是类似

"react-router-dom": "^5.1.2",
import {useHistory} from 'react-router-dom'
import {createHashHistory} from 'history';
const history1 =  createHashHistory();
console.log(history1);
function AandleClick() {
    let history = useHistory();
    console.log(history);
    return <div>11111</div>
}
class U extends Component {
    state = {};
   
    render() {
        return (
            <div>123
                <Link to={'/'}>to</Link>
                <button type="button" onClick={()=>{}}>
                     Go home
                </button>
                <AandleClick />
            </div>
        );
    }
}
export default U;
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐