gpt4 book ai didi

javascript - React/Router/MemoryRouter - 如何传递历史属性并在子组件中使用 push()?

转载 作者:行者123 更新时间:2023-12-04 15:32:11 25 4
gpt4 key购买 nike

我正在构建一个 React 应用程序,我不想在其中更新浏览器中的 URL。我没有使用“react-router-dom”,而只使用“react-router”和 MemoryRouter(https://reacttraining.com/react-router/web/api/MemoryRouter)。 history.push() 可直接在组件语句中使用,但我希望将历史传递给这些主要组件的子组件的子组件,但该属性未定义。

这是主 App.js 中的路由器部分(组件 Home 和 ScreeningTool 可以按预期访问 this.props.history.push()):

...
import {Route, MemoryRouter} from "react-router";
...
<MemoryRouter>
<Route exact path="/" component={Home} />
<Route path="/screening-tool" component={ScreeningTool} />
</MemoryRouter>
...

Home 和 ScreeningTool 都使用子组件 AppLink,它生成一个“链接”以在 Home 和 ScreeningTool 之间导航,就像这样(注意我将“历史”作为 Prop 传递):

Home.js:
...
<AppLink
url="/"
label="Screening Tool"
history={this.props.history}
/>
...

AppLink.js:
...
<div className="pseudo-link">
<span onClick={() => this.props.history.push(this.props.url)}>
{this.props.label}
</span>
</div>
...

上面的代码有效。但是 Home 中有子组件,它们将创建自己的 AppLinks 以及曾孙组件。我不想将 history 属性作为组件 Prop 从 Parent 传递到 Child 到 GrandChild 组件,因为这似乎效率不高。我发现了以下 stackoverflow 问题,但这些选项都不适合我:

this.props.history.push works in some components and not others

react-router getting this.props.location in child components

我尝试了上面第二个 URL 中描述的更新的“userHistory”:

...
import { useHistory } from 'react-router';
...
render() {
let history = useHistory();
return (
<div className="pseudo-link">
<span onClick={() => history.push(this.props.url)}>
{this.props.label}
</span>
</div>
);
}
...

但我得到 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. .

我尝试使用 withRouter如此处定义 https://reacttraining.com/react-router/web/api/withRouter但我得到 Error: Invariant failed: You should not use <withRouter(PseudoLink) /> outside a <Router> .

最后,this.props.history.push works in some components and not others 的可接受答案以代码块 export default withRouter(connect(mapStateToProps, matchDispatchToProps)(ChildView)); 结尾但没有解释 mapStateToProps 或 matchDispatchToProps 从何而来?

我认为问题在于我使用的是 MemoryRouter 而不是来自“reacto-router-dom”的普通/最常见路由器。

谁能帮帮我?

最佳答案

useHistory 是一个 Hook,因此它应该在功能组件中使用,而不是在基于类的组件中使用。

最后,this.props.history.push 的公认答案在某些组件中有效,而在其他组件中无效,以代码块 export default withRouter(connect(mapStateToProps, matchDispatchToProps)(ChildView)); 结尾;但没有解释 mapStateToProps 或 matchDispatchToProps 从何而来?

-如果你不使用 redux 那么你可以使用

export default withRouter(yourComponentName);

更新

我已经将 AppLink 组件更改为此并且它工作正常

import React from "react";
import "./AppLink.css";
import { useHistory } from 'react-router';

const AppLink = props => {
const history = useHistory();
return (
<div
className="app-link-button"
onClick={() => history.push(props.url)}
>
<span>{props.label}</span>
</div>
);
};

export default AppLink;

关于javascript - React/Router/MemoryRouter - 如何传递历史属性并在子组件中使用 push()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61031252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com