Reactjs 在使用Redux';后,历史将在我的react应用程序中作为儿童道具消失;s connect()?
我正在学习React和Redux,我的示例应用程序有问题。我正在尝试连接一个应用程序,该应用程序将根据是否已登录而导航到登录页或主页 应用层:Reactjs 在使用Redux';后,历史将在我的react应用程序中作为儿童道具消失;s connect()?,reactjs,redux,react-router,react-redux,Reactjs,Redux,React Router,React Redux,我正在学习React和Redux,我的示例应用程序有问题。我正在尝试连接一个应用程序,该应用程序将根据是否已登录而导航到登录页或主页 应用层: import Login from './../connectors/LoginConnector' import Index from './../connectors/IndexConnector' import Home from './../connectors/HomeConnector' const App = props => {
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 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
在我添加索引之前(当“/”直接路由到Login
时),应用程序正在工作,但在添加索引之后,我得到了。似乎在使用React Router和Redux时,道具的历史
部分正在被擦除,或者以某种方式没有传递到索引
的子组件。如果我在索引
视图顶部打印道具
,然后打印登录
视图,我会得到{match:{…},location:{…},history:{…},staticContext:undefined,username:null,}
然后{username:null,password:null,loggedIn:false,Login:ƒ}
。如何防止登录
丢失重要的道具,如历史
?要通过组件的道具访问路由器对象(即历史),组件必须通过路由
呈现,或者应该使用withRouter高阶组件包装
由于Login
组件是在另一个组件的呈现方法中使用JSX呈现的,所以在导出它之前,您应该使用高阶组件对其进行包装,如下所示
使用路由器导出默认值(登录)代码>谢谢,这有助于解决问题并消除错误。然而,我仍然没有得到预期的行为-也就是说,如果我登录,然后导航到“/”,它会在应该将我发送到主页时发送我登录(页面重新加载状态将恢复为初始状态)-你知道为什么会这样吗?请检查。页面重新加载时状态将刷新,您需要使用中间件。如果不需要中间件,也可以使用localStorage
。
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)