我是新来的反应。在我的React应用程序中,我有一个列出所有产品项的产品组件。在fetch function
从服务器上被处理redux-thunk
。但我无法访问state
组件中的,请'products'
始终注意变量-is undefined
。这是获取数据的正确方法吗?
在我Products.js
,
import Spinner from '../../components/Spinner/Spinner';
import { connect } from 'react-redux';
import { GetProductDataAction } from '../../redux/Product/Product.actions';
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
products: [],
}
}
async componentDidMount() {
const product = await this.props.getProductsData();
this.setState({
products: this.state.product,
loading: false
})
}
render() {
const { product } = this.state;
return (
<>
{
this.state.loading || !this.state.products ?
<Spinner />
:
<section className="products-overview-container">
<div className="product-container">
{
products.map(({ ...otherProps }) => {
return <Product key={otherProps._id}
{...otherProps} />
})
}
</div>
</section>
}
</>
);
}
}
const mapStateToProps = (state) => ({
products: state.product,
});
const mapDispatchToProps = (dispatch) => {
return {
getProductsData: () => {
dispatch(GetProductDataAction());
},
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Products);
在我的Product.action.jsx中,
import axios from "axios";
import ProductActionTypes from './Product.types';
export const GetProductDataAction = () => {
return async (dispatch) => {
try {
const res = await axios.get("http://127.0.0.1:3000/products");
const { data } = res;
dispatch({
type: ProductActionTypes.GET_PRODUCT_DATA_SUCCESS,
payload: data
});
console.log('Getting Tour Data Successfully');
} catch (error) {
// error code
}
};
};
这是您需要进行的更改:
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
products: []
};
}
async componentDidMount() {
const products = await this.props.getProductsData();
this.setState({
products,
loading: false
});
}
render() {
const { products } = this.state;
return (
<>
{this.state.loading || !this.state.products ? (
<Spinner />
) : (
<section className="products-overview-container">
<div className="product-container">
{products.length && products.map(({ ...otherProps }) => {
return <Product key={otherProps._id} {...otherProps} />;
})}
</div>
</section>
)}
</>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句