React props 被传递了,但是只有 render() 读取了 props?

React props is passed, but only render() reads props?

我找不到与地雷相关的情况,但是我的问题是 TypeError: Cannot read property 'props' of undefined.

的常见错误

奇怪的是,这个错误只发生在我上面定义的方法中 render()

render() 内部,我可以毫无错误地访问。 React 开发工具显示我什至可以访问道具。

代码如下:

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 绑定。

您需要在点击处理程序上使用 .bind

<button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>

这是因为你的方法 handleLogout 有它自己的上下文。为了将 class 的 this 值传递给您的方法,必须执行以下两项操作之一:

1) 将其绑定在 class:

的构造函数中
constructor(props) {
  super(props)
  this.handleLogout = this.handleLogout.bind(this)
}

2) 您将 handleLogout 方法声明为箭头函数

handleLogout = () => {
  console.log(this.props)
}

我相信这在非 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);
}