首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React props被传递,但只有render()读取props?

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

Stack Overflow用户
提问于 2019-03-14 05:45:46
回答 3查看 67关注 0票数 1

我找不到与mines相关的情况,但是我的问题是我有一个常见的TypeError: Cannot read property 'props' of undefined错误。

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

render()内部,我可以毫无错误地进行访问。React dev tools显示我甚至可以访问道具。

代码如下:

代码语言:javascript
复制
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绑定。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-14 05:51:11

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

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

代码语言:javascript
复制
constructor(props) {
  super(props)
  this.handleLogout = this.handleLogout.bind(this)
}

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

代码语言:javascript
复制
handleLogout = () => {
  console.log(this.props)
}
票数 2
EN

Stack Overflow用户

发布于 2019-03-14 05:52:45

我相信这不是绑定在非es6中。因此,您可以使用构造函数绑定它,也可以使用es6类型函数

代码语言:javascript
复制
handleLogout = () => {
    Auth.logout()
    this.props.history.replace('/login')
}

我不能试这个,但你也可以做一个

代码语言:javascript
复制
constructor(props) {
  super(props);
  // Don't call this.setState() here!

  this.handleLogOut= this.handleLogOut.bind(this);
}
票数 1
EN

Stack Overflow用户

发布于 2019-03-14 05:49:22

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

代码语言:javascript
复制
<button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55151671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档