Reactjs 无法读取属性';推动';在反应中未定义的
Reactjs 无法读取属性';推动';在反应中未定义的,reactjs,react-router,Reactjs,React Router,import React,{PropTypes}来自'React'; 导出默认类登录扩展React.Component{ 建造师(道具){ 超级(道具) this.handleLogin=this.handleLogin.bind(this) } handleLogin(事件){ event.preventDefault() //在此处执行一些登录逻辑,如果成功: this.props.history.push(`/Home`) } render(){ 返回( ) } }如果您使用的是react
import React,{PropTypes}来自'React';
导出默认类登录扩展React.Component{
建造师(道具){
超级(道具)
this.handleLogin=this.handleLogin.bind(this)
}
handleLogin(事件){
event.preventDefault()
//在此处执行一些登录逻辑,如果成功:
this.props.history.push(`/Home`)
}
render(){
返回(
)
}
}
如果您使用的是react router,则需要使用router将组件包装起来,以便将历史道具注入到组件中
import {withRouter} from 'react-router-dom';
...
export default withRouter(MyComponent);
此外,无论您使用什么组件,它都必须是顶层路由器组件的子组件。看起来您的组件没有用路由器包装。用路由器将其包裹起来
import React, { PropTypes } from "react";
import { withRouter } from "react-router-dom";
class Login extends React.Component {
constructor(props) {
super(props);
this.handleLogin = this.handleLogin.bind(this);
}
handleLogin(event) {
event.preventDefault();
// do some login logic here, and if successful:
this.props.history.push(`/Home`);
}
render() {
return (
<div>
<form onSubmit={this.handleLogin}>
<input type="submit" value="Login" />
</form>
</div>
);
}
}
export default withRouter(Login);
import React,{PropTypes}来自“React”;
从“react router dom”导入{withRouter};
类登录扩展了React.Component{
建造师(道具){
超级(道具);
this.handleLogin=this.handleLogin.bind(this);
}
handleLogin(事件){
event.preventDefault();
//在此处执行一些登录逻辑,如果成功:
this.props.history.push(`/Home`);
}
render(){
返回(
);
}
}
使用路由器导出默认值(登录);
默认情况下,使用不能在react router 4中使用browserHistory,因为您可以在react router 3中使用,但您可以使用不同的方式通过路由器或上下文推送,但我建议
与路由器HOC一起使用。
您应该使用withRouter高阶组件,并将其包装到将推送到历史的组件。例如:
import React from "react";
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/HOME");
}
...
}
export default withRouter(MyComponent);
使用路由器包装组件,使其具有历史记录道具,以便可以使用推送功能以下是使其工作的要求:
index.js所需的导入:
import { Provider } from 'react-redux';
import { createHashHistory } from 'history';
import { ConnectedRouter, connectRouter, routerMiddleware } from 'connected-react-router';
在主App.js中,您需要:
const history = createHashHistory();
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
rootEl,
);
当我使用上面的代码时,我得到如下错误:当我使用上面的代码时,你不应该在a之外使用或与Router()一起使用,我得到以下错误:当我使用上面的代码时,你不应该在a之外使用或与Router()一起使用,我得到以下错误:你不应该使用或与Router()一起使用这与我最后的评论有关。您需要确保您的父组件包装在顶级的
组件中,在此范围之外使用它将无法工作,因为正是此组件将历史道具注入到您的组件中。从“React”导入React;从“react Router dom”导入{BrowserRouter as Router,Route};//从“react router”导入{hashHistory};从“./Login”导入登录名;导出默认类App extensed React.Component{render(){return()}}这是我的App.js,可以吗?
import { push as RouterPush } from 'react-router-redux';