在React应用程序中更改商店中的路线 [英] Change route from store in React application
问题描述
我有一个React组件,它接受用户名和密码并将其发送以进行身份验证.如果身份验证成功,则页面应移至呈现其他组件的其他路由.
I have a React component that takes in username and password and sends it for authentication. If authentication is successful, the page should move to a different route which renders another component.
现在的问题是,我不确定如何更改商店的路线?即不使用React Router的<Link>
组件?我知道我们可以使用this.props.history.push(/url)
以编程方式更改路线,但只能在使用<Route>
的React Component内部使用它,而不能在商店中使用.
Now the problem is, I am not sure how I can change route from my store? i.e. without using the <Link>
component of React Router? I know that we can use this.props.history.push(/url)
to change route programatically, but it can only be used inside a React Component using <Route>
, not from the store.
我正在使用带有MobX的React16进行状态管理,并使用ReactRouter V4进行路由.
I am using React16 with MobX for state management, and ReactRouter V4 for routing.
商店:
class Store {
handleSubmit = (username, password) => {
const result = validateUser(username, password);
// if result === true, change route to '/search' to render Search component
}
}
登录组件:
const Login = observer(({ store }) => {
return (
<div>
<form onSubmit={store.handleSubmit}>
<label htmlFor="username">User Name</label>
<input type="text" id="username" onChange={e => store.updateUsername(e)} value={store.username} />
<label htmlFor="password">Password</label>
<input type="password" id="password" onChange={e => store.updatePassword(e)} value={store.password} />
<input type="submit" value="Submit" disabled={store.disableSearch} />
</form>}
</div>
)
})
主要应用程序组件:
import { Router, Route, Link } from "react-router-dom";
@observer
class App extends React.Component {
render() {
return (
<Router history={history}>
<div>
<Route exact path="/"
component={() => <Login store={store} />}
/>
<Route path="/search"
component={() => <Search store={store} />}
/>
</div>
</Router>
)
}
}
推荐答案
您可以在单独的模块中创建history
,然后将其导入到主应用程序的Component和Store中:
You could create the history
in a separate module, and import that both in your main app Component and Store:
// history.js
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export default history;
// Store.js
import history from './history';
class Store {
handleSubmit = (username, password) => {
const result = validateUser(username, password);
if (result) {
history.push('/search');
}
}
}
// App.js
import { Router, Route, Link } from "react-router-dom";
import history from './history';
@observer
class App extends React.Component {
render() {
return (
<Router history={history}>
<div>
<Route exact path="/"
component={() => <Login store={store} />}
/>
<Route path="/search"
component={() => <Search store={store} />}
/>
</div>
</Router>
)
}
}
这篇关于在React应用程序中更改商店中的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!