Я новичок в реакции. В моем приложении для реагирования у меня есть компонент продукта, в котором перечислены все элементы продукта. fetch function
с сервера обрабатывается redux-thunk
. Но я не могу получить доступ к state
в своих компонентах, продолжаю замечать, что переменная - 'products'
есть 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.info('Getting Tour Data Successfully');
} catch (error) {
// error code
}
};
};
Следуя официальному документу Redux Thunk.
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
Это означает, что второй параметр должен быть getState
. Вы можете получить доступ к состоянию отсюда.
вот изменения, которые вам нужно сделать:
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>
)}
</>
);
}
}