我正在尝试使用React.js实现身份验证。我正在关注这个tutorial
当我使用本教程运行示例时,效果很好。
当我在项目中实现教程解决方案时,它会成功一半。一旦我进入“登录”路线,它将在控制台中给我以下错误:
警告:失败的上下文类型:在router
中未指定必需的上下文Login
。检查RoutingContext
的渲染方法。
如果刷新页面,则表明我已登录并且可以正常工作,只是因为错误应用程序停止了。我正在使用相同的库。
这是我使用的代码(Fiddle):
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'
import auth from './auth'
const App = React.createClass({
getInitialState() {
return {
loggedIn: auth.loggedIn()
}
},
updateAuth(loggedIn) {
this.setState({
loggedIn: loggedIn
})
},
componentWillMount() {
auth.onChange = this.updateAuth
auth.login()
},
render() {
return (
<div>
<ul>
<li>
{this.state.loggedIn ? (
<Link to="/logout">Log out</Link>
) : (
<Link to="/login">Sign in</Link>
)}
</li>
<li><Link to="/about">About</Link></li>
<li><Link to="/dashboard">Dashboard</Link> (authenticated)</li>
</ul>
{this.props.children || <p>You are {!this.state.loggedIn && 'not'} logged in.</p>}
</div>
)
}
})
const Dashboard = React.createClass({
render() {
const token = auth.getToken()
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
</div>
)
}
})
const Login = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState() {
return {
error: false
}
},
handleSubmit(event) {
event.preventDefault()
const email = this.refs.email.value
const pass = this.refs.pass.value
auth.login(email, pass, (loggedIn) => {
if (!loggedIn)
return this.setState({ error: true })
const { location } = this.props
if (location.state && location.state.nextPathname) {
this.context.router.replace(location.state.nextPathname)
} else {
this.context.router.replace('/')
}
})
},
render() {
return (
<form onSubmit={this.handleSubmit}>
<label><input ref="email" placeholder="email" defaultValue="vedran" /></label>
<label><input ref="pass" placeholder="password" /></label> (hint: password1)<br />
<button type="submit">login</button>
{this.state.error && (
<p>Bad login information</p>
)}
</form>
)
}
})
const About = React.createClass({
render() {
return <h1>About</h1>
}
})
const Logout = React.createClass({
componentDidMount() {
auth.logout()
},
render() {
return <p>You are now logged out</p>
}
})
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="login" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>
), document.getElementById('example'))
我究竟做错了什么?
似乎这条线产生了问题:
contextTypes: {
router: React.PropTypes.object.isRequired
},
最佳答案
似乎已安装的react-router版本有问题?链接中的代码示例适用于react-router v2.x
关于javascript - React.js-导航路线时控制台中的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35838927/