react生命周期方法-正确的过滤方式



我是新手。我有一个产品页面组件,它是一个显示特定产品的页面。我想做的是,这个ProductPage在产品中找到特定的产品(这是一个存储为道具的对象数组(,并在渲染之前将其保存为状态。

我犯了这些错误。我无法从阵列中筛选出单个产品。

1) currentProduct is not defined.
2)Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

我应该使用哪种生命周期方法来解决这个问题?我很困惑。有人能给我解释一下吗?

在我的ProductPage.js中,

import React, { Component } from 'react';
import { connect } from 'react-redux';
class ProductPage extends Component {
constructor(props) {
super(props)
this.state = {
product: [],
productId: this.props.match.params._id,
}
this.productsFiltering = this.productsFiltering.bind(this);
}
// update the state so that a product can be rendered
componentDidUpdate() {
const currentProduct = this.productsFiltering(this.state.productId);
this.setState({
product: currentProduct,
})
}

// find a product based on the Id 
// pass the _id from url to find out the single product
productsFiltering = (productId) => {
const productArray = this.props.products;
return productArray.find(product => product._id === productId)
}
render() {
// error
const {name, price, description} = product; 
return (
<div>
<span>{product.name}</span>
<span>{product.price}</span>
<span>{product.description}</span>
</div>
)
}
}
const mapStateToProps = (state) => ({
products: state.productsContainer,
});

export default connect(
mapStateToProps,
)(ProductPage);

根本问题是您正在将道具复制到状态,这是不需要做的。

ProductPage显示产品并且不会更改,因此不需要任何状态。只需获取匹配的产品并将其存储在变量中,然后进行渲染。不需要setState()

如果将代码更改为,则可以删除这两个错误

class ProductPage extends Component {
constructor(props) {
super(props);
this.state = {
product: []
};
this.productsFiltering = this.productsFiltering.bind(this);
}
// update the state so that a product can be rendered
componentDidUpdate() {
const productId = this.props.match.params._id;
if (productId && this.state.product._id != productId) {
const currentProduct = this.productsFiltering(productId);
if (currentProduct) {
this.setState({
product: currentProduct
});
}
}
}
// find a product based on the Id
// pass the _id from url to find out the single product
productsFiltering = (productId) => {
const productArray = this.props.products;
if(productArray.length){
return productArray.find((product) => products._id === productId);
}
};
render() {
const { name, price, description } = this.state.product || {};
return (
<div>
<span>{product.name}</span>
<span>{product.price}</span>
<span>{product.description}</span>
</div>
);
}
}
const mapStateToProps = (state) => ({
products: state.productsContainer
});
export default connect(mapStateToProps)(ProductPage);

--始终检查未定义或空属性

--如果新状态不断变化,则不要在componentDidMount中使用setState

--避免使用直接从props驱动的state,因为这是一种糟糕的做法,并且您可以获得stale props

最新更新