我正在构建一个小应用程序来学习 React 和 Meteor。
要求用户输入一个位置,根据这个位置,用户被路由到一个新页面,该位置显示在页面顶部,以及基于该位置的数据库中的一些数据(还没有,这是我的)下一步)。
我将位置存储在组件的状态中。现在如果用户可以更改位置就好了。
这很简单:只需更新状态即可,瞧。或者说我是这么想的。现在的问题是 URL 没有更新,这看起来很愚蠢。
然后我想:“好吧,让我们检查一下旧位置(在状态中)和新位置(来自输入)是否不同,如果是,则设置重定向状态”
在我的渲染函数中,如果设置了重定向,我只会再次将用户路由到同一页面,但现在页面不会重新加载。有任何想法吗?
我知道现在有一千个问题关于 React Router v4,因为他们最近刚刚更新了版本。过去几个小时我一直在阅读文档,但无法理解它。
import React, { Component } from 'react';
import { Route, Redirect } from 'react-router'
import LocationPicker from './LocationPicker'
export default class LocationDisplay extends Component {
constructor () {
super();
this.setLocation = this.setLocation.bind(this);
this.state = {redirect: false};
}
setLocation(value) {
this.setState({locationId: value});
if (this.state.locationId != value) {
this.setState({redirect : true})
};
}
componentWillMount() {
this.setState({
locationId: this.props.match.params.locationId,
});
}
render () {
return (
this.state.redirect
?
<Redirect push to={{
pathname: `/location/${this.state.locationId}`
}}/>
:
<div>
<LocationPicker
returnLocation={this.setLocation}
locationId={this.state.locationId}
/>
<h1>Please find below all recommendations for {this.state.locationId}</h1>
</div>
)
}
}
这是我的路线:
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import { render } from 'react-dom';
import App from './App';
import LocationPicker from './LocationPicker';
import LocationDisplay from './LocationDisplay';
Meteor.startup(() => {
render(
<Router>
<div>
<Route exact path="/" component={LocationPicker}/>
<Route path="/location/:locationId" component={LocationDisplay}/>
</div>
</Router>,
document.getElementById('render-target')
);
});
Update:
我尝试使用<Link>
代替<Redirect>
,但这具有相同的效果。更重要的是,它现在根本不更新 URL。
render () {
return (
this.state.redirect
?
<Link to={{
pathname: `/location/${this.state.locationId}`
}}/>
:
<div>
<LocationPicker
returnLocation={this.setLocation}
locationId={this.state.locationId}
/>
<h1>Please find bellow all recommendations for {this.state.locationId}</h1>
</div>
)
}
任何有关该问题的基本语言解释也将不胜感激。我只是还没到那里:(
干杯很多