我正在学习React和Redux,我的示例应用程序出了问题。我正在尝试连接一个将导航到登录页面或主页的应用程序,具体取决于它是否已经登录。
应用层:
import Login from './../connectors/LoginConnector'
import Index from './../connectors/IndexConnector'
import Home from './../connectors/HomeConnector'
const App = props => {
return(
<Router>
<div>
<Route exact path="/" component={Index}/>
<Route path="/login" component={Login}/>
<Route path="/home" component={Home}/>
</div>
</Router>
)
}
export default App
索引视图:
const Index = (props) => {
if (props.loggedIn) {
return(
<Home/>
);
} else {
return (
<Login/>
)
}
}
export default Index
索引容器组件:
const mapStateToProps = (state) => {
console.log("Index state = ", state)
return {...state}
}
export default connect(mapStateToProps)(Index)
登录视图:
const Login = (props) => {
console.log("Login props = ", props)
let user, pass
const login = e => {
e.preventDefault();
props.login(user.value, pass.value)
props.history.push("/home");
};
return(
<div>
<h1>Login</h1>
<form onSubmit={login}>
<label> Username:
<input type="text" className="form-control col-md-12" ref = {node => user = node}/>
</label>
<label> Password:
<input type="password" className="form-control col-md-12" ref = {node => pass = node}/>
</label>
<br />
<input type="submit" value="Submit" />
</form>
</div>
)
}
export default Login
登录容器组件:
const mapStateToProps = (state) => {
return {...state}
}
const mapDispatchToProps = dispatch => {
return {
login: (user, pass) => dispatch(logIn(user, pass))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)
在添加索引之前应用程序正在运行(当&#34; /&#34;直接路由到Login
时),但在添加索引后我获得this error when I try to log in。似乎在使用React Router和Redux时,history
的{{1}}部分正在被删除或以某种方式不会传递给props
的子组件。如果我打印Index
视图顶部的props
,然后打印Index
视图,我会Login
然后{match: {…}, location: {…}, history: {…}, staticContext: undefined, username: null, …}
。如何防止{username: null, password: null, loggedIn: false, login: ƒ}
丢失重要道具,例如Login
?
答案 0 :(得分:0)
要通过组件的道具访问路由器对象(即历史记录),组件必须通过Route
呈现,或者应该使用withRouter更高阶组件进行包装。
由于Login
组件在另一个组件的render方法中使用JSX呈现,因此在导出它之前,应该使用withRouter高阶组件将其包装起来,如下所示。
export default withRouter(Login);