我有以下代码:-
import React, { Component } from "react";
import { useHistory } from "react-router-dom";
class clusterServersDropdown extends Component {
constructor() {
super();
this.state = {
clusterslist: [],
servertype: [],
selectserver: "",
selectcluster: ""
};
}
componentDidMount() {
this.setState({
clusterslist: [
{ label: "cluster1", servertype: ["test1", "test2", "test3"] },
{ label: "cluster2", servertype: ["test1", "test2", "test3"] }
]
});
}
selectclusterChange(e) {
this.setState({ selectcluster: e.target.value });
this.setState({
servertype: this.state.clusterslist.find(
(x) => x.label === e.target.value
).servertype
});
}
routeChange = (e) => {
this.setState({ selectserver: e.target.value}, () => {
console.log(this.state.selectserver);
let path = "http://localhost:3000/inventory/cluster/" + this.state.selectcluster +"/servertype/" + this.state.selectserver;
console.log(path);
withRouter(path);
});
};
render() {
return (
<div>
<center>
<h1>
Implement cascading Dropdown list
<h2>
ReactJS tutorials
<hr />
<select
value={this.state.selectcluster}
onChange={this.selectclusterChange.bind(this)}
>
<option>-- Select --</option>
{this.state.clusterslist.map((x) => {
return <option>{x.label}</option>;
})}
</select>
<select
value={this.state.selectserver}
onChange={this.routeChange}
>
<option>--------selection disabled------</option>
{this.state.servertype.map((x) => {
return <option>{x}</option>;
})}
</select>
</h2>
</h1>
</center>
</div>
);
}
}
export default clusterServersDropdown;
根据我得到的输出,我在此处创建链接后尝试重定向到另一个链接。当我执行 console.log 时,我的链接被打印为 http://localhost:3000/inventory/cluster/cluster1/servertype/test1 ,我需要重定向到该链接。我过去曾使用过 usehistory,但由于它是一个钩子(Hook),我无法在这里使用它。我有什么想法可以在这里使用路由器吗?
最佳答案
withRouter
是一个高阶组件,导入它并装饰 ClusterServersDropdown
组件。
import { withRouter } from "react-router-dom";
class ClusterServersDropdown extends Component {
...
}
export default withRouter(ClusterServersDropdown);
这会注入(inject)route props (history
、location
、match
) 到您的类组件中。从 props
访问 history
对象。
routeChange = (e) => {
this.setState({ selectserver: e.target.value}, () => {
console.log(this.state.selectserver);
let path = "http://localhost:3000/inventory/cluster/" + this.state.selectcluster +"/servertype/" + this.state.selectserver;
console.log(path);
this.props.history.push(path);
});
};
关于reactjs - 无法在类组件中使用 usehistory,withrouter 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70811896/