【问题标题】:Cannot read property 'state' of undefined although using arrow-syntax尽管使用箭头语法,但无法读取未定义的属性“状态”
【发布时间】:2021-07-18 07:01:32
【问题描述】:

在我的示例中,我从 API 获取产品对象。产品有ImageIds,指的是图片,我也是在获取产品后从API中获取的。

class ProductDetails extends Component {
    state = {
        productId: this.props.match.params.id,
        product: null,
        imagePaths: [],
        currentImagePath: null,
        loading: true
    }
    constructor(props) {
        super(props);
        this.request = getDefaultRequest();
    }
    componentDidMount = () => {
        this.fetchProduct();
    }
    // Api calls
    fetchProduct = async () => {
        const response = await this.request.get(`http://localhost:8080/product/Id=${this.state.productId}`);
        let { product } = response.data;
        this.setState({
            product
        }, () => {
            this.fetchImages().then((images) => {
                this.setImagePaths(images);
            });
        });
    }

    fetchImages = async () => {
        let { product } = this.state;
        let images = [];
        for (let i = 0; i < product.ProductImageIds.length; i++) {
            let currentProducImageId = product.ProductImageIds[i];
            let response = await this.request.get(`http://localhost:8080/productImage/Id=${currentProducImageId}`);
            images.push(response.data.productImage);
        }
        return Promise.resolve(images);
    }
    setImagePaths = (images) => {
        let imagePaths = images.map(image => {
            return image.absolutePath.split("public")[1].replaceAll("\\", "/");
        });
        this.setState({
            imagePaths,
            currentImagePath: imagePaths[0],
            loading: false
        });
    }

    render() {
      let { product, loading } = this.state;
        if (!loading) {
            return (
                <div>
                    <h2 className="t-center">{product.name}</h2>
                    <div className="wrap-product-details">
                        <ProductQuickWatch
                            imagePaths={this.state.imagePaths}
                            currentImagePath={this.state.currentImagePath}
                            productName={this.state.product.name}
                            productId={this.state.product._id}
                            orientation="vertical">

                        </ProductQuickWatch>
                    </div>
                </div>
            );
        }
        return (
            <LoadingCircle
                usePortal={true}
                loading={true} />
        )
      }

但现在我得到“TypeError: Cannot read property 'state' of undefined”

我对此进行了调试并意识到一切正常,直到将加载状态设置为 false(在 setImagePaths() 中)。

如果我省略将加载设置为 false,则一切正常。 但我不知道为什么。如果查看 render(),加载状态很重要。

我对此进行了研究,一个可能的解决方案是在构造函数中绑定函数。 但通常如果你使用箭头语法“this”不是问题。我也试过了,还是不行:/。

错误:

TypeError: Cannot read property 'state' of undefined
new i
C:/Users/David/Documents/GitHub/React/ShoppingTemplate/src/Store/WithStore.jsx:22
  19 |   children: null,
  20 | };
  21 | 
> 22 | constructor(props, context) {
     | ^  23 |   super(props, context);
  24 |   this.state = mapStateToProps({ ...context.state });
  25 |   this.updateStateProps = this.updateStateProps.bind(this);
▶ 19 stack frames were collapsed.
ProductDetails.setImagePaths
C:/Users/David/Documents/GitHub/React/ShoppingTemplate/app/src/Components/Category/ProductDetails.jsx:47
  44 | let imagePaths = images.map(image => {
  45 |     return image.absolutePath.split("public")[1].replaceAll("\\", "/");
  46 | });
> 47 | this.setState({
     | ^  48 |     imagePaths,
  49 |     currentImagePath: imagePaths[0],
  50 |     loading: false
View compiled
(anonymous function)
C:/Users/David/Documents/GitHub/React/ShoppingTemplate/app/src/Components/Category/ProductDetails.jsx:28
  25 |         product
  26 |     }, () => {
  27 |         this.fetchImages().then((images) => {
> 28 |             this.setImagePaths(images);
     | ^  29 |         });
  30 |     });
  31 | }

【问题讨论】:

  • 我在setImagePaths 中看不到任何this.state 呼叫。说问题出在哪里的错误?你能在你的问题中提供实际的错误和堆栈跟踪吗?
  • 问题在WithStore HOC,你能分享一下吗?
  • @MichaelRovinsky 这没有帮助,我使用箭头语法来防止有关“this”的任何错误。
  • @MichaelRovinsky 没用
  • @MichaelRovinsky setImagePaths 是一个箭头函数。 bind(this) 没有任何意义。此外,this.setImagePaths(images).bind(this) 执行setImagePaths 方法并将this 绑定到该方法返回的任何内容。在这种情况下,它返回 undefined。

标签: javascript reactjs react-state


【解决方案1】:

有趣的讨论 ;) 我会将其作为答案,尽管它并没有真正回答。但是它太长了,而且很杂乱。两点:

  1. 这部分
    new i
    C:/Users/David/Documents/GitHub/React/ShoppingTemplate/src/Store/WithStore.jsx:22

很有趣,因为它出现在错误上下文中,但据我所知,它没有出现在代码中。那么这是从哪里来的呢?您的问题中可能缺少一些信息。

  1. 这是一个相当复杂的this 和=&gt; 链。我没有看到错误,但是通过“眼睛”进行调试很糟糕。添加大量console.logs(1)、console.logs(2) 等等,看看代码到底在哪里中断。当你有线路时,输出this 和this.state。只有两个选项可能是错误的:错误的 this 或 this.state 只是没有定义。有了这些信息,在大多数情况下修复错误就相对简单了。

【讨论】:

  • 我用你说的类似方法试过了。我将“this”记录到控制台并查看状态,但没有问题。与此同时,我解决了这个问题。我发现我使用库有点错误,这导致了问题。问题出在 ProductQuickWatch 组件中。不知何故,我以前使用过这个组件,它工作得很好。不知道为什么它在这种情况下不起作用。
  • 很高兴听到。根据我的经验,极限日志记录几乎在所有情况下都有帮助。我希望有人在我开始编程时告诉我...
  • 是的,但不幸的是,这并没有解决这种情况下的问题。
  • 虽然 IMO 控制台调试是一种合法的方法,但您仍然应该熟悉设置断点,并能够在通过附加的调试器执行代码时有条不紊地逐步执行代码。 Chrome(以及可能大多数带有开发工具的浏览器)将使断点和调试器变得微不足道,学习部分是在哪里设置断点,并在单步执行代码时了解单步执行与函数调用之间的区别。
  • 嗯,这很简单,F5 与 F6...我过去常常通过在 Java 中逐步调试,但现在已经远离它了。对我来说,这种需求有些消失了,而且日志记录功能更强大,尤其是在大型数据集步进的情况下,这是不可行的。记录总是如此。所以对于 JS,我个人从来没有费心去设置它。不过,如果那是您喜欢的方式,请务必。
【解决方案2】:

我发现,它必须与我在 ProductQuickWatch 组件调用“pure-react-carousel”。 Here 是一个类似的错误。当我删除它时,我可以将加载状态设置为 false。 我必须对这个错误进行更多研究。谢谢你的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-11-28
    • 1970-01-01
    • 2019-07-25
    • 2020-11-05
    • 2021-07-07
    相关资源
    最近更新 更多