【问题标题】:React props is passed, but only render() reads props?React props 传了,但只有 render() 读取 props?
【发布时间】:2019-03-13 21:45:46
【问题描述】:

我找不到与地雷相关的情况,但是我的问题是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绑定。

【问题讨论】:

    标签: reactjs react-props


    【解决方案1】:

    这是因为你的方法handleLogout 有它自己的上下文。为了将类的this 值传递给您的方法,必须做以下两件事之一:

    1) 将其绑定到类的构造函数中:

    constructor(props) {
      super(props)
      this.handleLogout = this.handleLogout.bind(this)
    }
    

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2021-02-01
          • 1970-01-01
          • 2018-12-28
          • 2018-04-06
          • 1970-01-01
          • 1970-01-01
          • 2019-08-11
          • 1970-01-01
          • 2023-03-08
          相关资源
          最近更新 更多