【发布时间】:2025-12-26 22:40:20
【问题描述】:
我正在用 React Js 构建一个有 2 个页面的小型 Web 应用程序。我正在我的主页上显示一些城市列表,这些城市是我通过 Axios 从 REST API 获取的。
我的任务是点击任何城市并获得它的名字。当我单击任何城市名称时,地址栏中的路线会更改,并添加了特定的城市 ID,但未显示具有城市名称的组件。当我重新加载页面时,它会显示该特定城市的名称,然后它就可以正常工作了。
我应该怎么做才能让它在不重新加载任何手册页的情况下正常工作?
以下是我的问题代码 sn-p:
应用组件(路由):
<BrowserRouter>
<div className="App">
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/:city_id" component={SecondTable} />
</Switch>
</div>
</BrowserRouter>
主页组件:
class Home extends Component {
state = {
cities: [],
name: ""
};
async componentDidMount() {
await axios.get("http://100.124.69.3:8080/api/v1/cities").then(res => {
this.setState({ cities: res.data });
console.log(res);
});
console.log(this.state.cities);
}
render() {
let postList = this.state.cities.map(city => {
return (
<div key={city.id}>
<p>
<BrowserRouter>
<Link to={"/" + city.id}>{city.name}</Link>
</BrowserRouter>
</p>
</div>
);
});
return (
<div className="align">
All Facilities (NCAL)
<div className="Modal1">{postList}</div>
</div>
);
}
}
SecondTable 组件:(我要显示城市名称的地方)
class SecondTable extends Component {
state = {
data: [(visible: false), (city: null)]
};
async componentDidMount() {
console.log(this.props);
let id = this.props.match.params.city_id;
await axios
.get("http://100.124.69.3:8080/api/v1/cities/" + id)
.then(res => {
this.setState({ city: res.data.name });
console.log(res);
});
console.log(this.state.city);
}
render() {
return <div className="align1">{this.state.city}</div>;
}
}
【问题讨论】:
-
在
Home组件中删除Link之前的BrowserRouter。 -
谢谢。感谢您的反馈。它现在正在工作。
-
不客气。好的,那么让我提供这个作为答案然后接受它:)
-
当然。谢谢@devserkan
-
@devserkan 考虑到相关问题,现在我得到了那个特定的城市名称。现在我单击一个模式对话框来更改城市的名称,但同样的事情再次发生,因为新名称正在显示,但在手动页面重新加载之后。我认为当我更改城市名称时,我的状态没有更新。由于我是新手,您能帮我解决这个问题吗?
标签: javascript reactjs react-router