gpt4 book ai didi

javascript - 为什么我收到无法读取未定义的属性 'state'?

转载 作者:行者123 更新时间:2023-12-01 00:53:59 25 4
gpt4 key购买 nike

我有一个构造函数突然停止工作,不知道为什么。

我有这个数据。如果您在第 24 行看到,它会被读出并实际上返回包括 Prop 在内的各种项目。然而,1 行之后,当我尝试写入状态时,它返回此错误。我不明白为什么,因为这里没有任何东西可以绑定(bind),而且它在某个时刻起作用了。

TypeError: Cannot read property 'state' of undefined
23 | super(props);
24 | console.log(this)
25 |
26 | this.state = {
| ^ 27 | loading: true,
28 | ...props.location.state,
29 | review: props.review,
import React, { Component } from 'react';

import { withFirebase } from '../Firebase';
import { AuthUserContext } from '../Session';

import { needsEmailVerification } from '../Session/withEmailVerification.js'

import NewCommentReactionPage from '../Comments/newReaction.js'
import NewReviewFeedbackPage from '../Comments/new.js'
import RequireEmailComponent from '../Errors/requireEmail.js'

const ReviewFeedbackPage = (props) => (
<AuthUserContext.Consumer>
{authUser => (
<ReviewFeedbackMain authUser={authUser} isLoggedIn={condition(authUser)} needEmail={needsEmailVerification(authUser)} {...props} />
)}
</AuthUserContext.Consumer>
);

class ReviewFeedbackBase extends Component {
constructor(props) {
super(props);

this.state = {
loading: true,
...props.location.state,
review: props.review,
newComment: '',
comments: [],
reactions: props.review ? props.review.count ? props.review.count.reactions ? props.review.count.reactions : {} : {} : {}
};

this.reactionAdded = this.reactionAdded.bind(this)
this.commentAdded = this.commentAdded.bind(this)
}


componentDidMount() {
...
}

componentDidUpdate(prevProps, prevState) {
...
}


commentAdded(newComment){
...
}

render() {
const { review, comments, reactions } = this.state;
const { isLoggedIn, needsEmail } = this.props;
return (
<div>
....
}
{isLoggedIn && needsEmail && <RequireEmailComponent toAction={{text: 'to react'}} />}
{isLoggedIn && !needsEmail &&
<div>
<NewCommentReactionPage review={review} reactionAdded={this.reactionAdded} />
<NewReviewFeedbackPage review={review} commentAdded={this.commentAdded} />
</div>
}


</div>
);
}
}

const ReviewFeedbackMain = withFirebase(ReviewFeedbackBase);

const condition = authUser => !!authUser;
export default ReviewFeedbackPage;

最佳答案

在您的代码中,您有 2 state :

this.state = {  // declaring state
loading: true,
...props.location.state, // referencing the state of ...props.location
review: props.review,
newComment: '',
comments: [],
reactions: props.review ? props.review.count ? props.review.count.reactions ? props.review.count.reactions : {} : {} : {}
};

您收到此错误是因为 props.locationundefined并且您正在尝试访问state来自它。

错误出现在第 26 行,因为它无法声明变量。

26 | this.state = {
| ^ 27 | loading: true,

不是构造函数中的问题,而是 ...props.location.state 中的问题.

既然您知道问题所在,您需要看看您想要做什么。

也许在传播之前做一些检查 props.location.state ?这取决于你。

关于javascript - 为什么我收到无法读取未定义的属性 'state'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com