我找不到与mines相关的情况,但是我的问题是我有一个常见的TypeError: Cannot read property 'props' of undefined错误。
奇怪的是,这个错误只发生在我在render()上面定义的方法上。
在render()内部,我可以毫无错误地进行访问。React dev tools显示我甚至可以访问道具。
代码如下:
import { Route } from 'react-router-dom'
import AuthService from '../../utils/authentication/AuthService'
import withAuth from '../../utils/authentication/withAuth'
const Auth = new AuthService()
class HomePage extends Component {
handleLogout() {
Auth.logout()
this.props.history.replace('/login')
}
render() {
console.log(this.props.history)
return (
<div>
<div className="App-header">
<h2>Welcome {this.props.user.userId}</h2>
</div>
<p className="App-intro">
<button type="button" className="form-submit" onClick={this.handleLogout}>Logout</button>
</p>
</div>
)
}
}
export default withAuth(HomePage)编辑:道歉。我也不想引起混淆,所以我要补充说,我也在使用@babel/plugin-proposal-class-properties来避免this绑定。
发布于 2019-03-14 05:51:11
这是因为你的方法handleLogout有它自己的上下文。为了将类的this值传递给您的方法,必须执行以下两项操作之一:
1)将其绑定到类的构造函数中:
constructor(props) {
super(props)
this.handleLogout = this.handleLogout.bind(this)
}2)将handleLogout方法声明为箭头函数
handleLogout = () => {
console.log(this.props)
}发布于 2019-03-14 05:52:45
我相信这不是绑定在非es6中。因此,您可以使用构造函数绑定它,也可以使用es6类型函数
handleLogout = () => {
Auth.logout()
this.props.history.replace('/login')
}我不能试这个,但你也可以做一个
constructor(props) {
super(props);
// Don't call this.setState() here!
this.handleLogOut= this.handleLogOut.bind(this);
}发布于 2019-03-14 05:49:22
您需要在单击处理程序上使用.bind。
<button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>https://stackoverflow.com/questions/55151671
复制相似问题