簡體   English   中英

如何從 redux-thunk 中的獲取操作中訪問 state?

[英]How to access the state from the fetching action in redux-thunk?

我是新來的反應。 在我的反應應用程序中,我有一個產品組件列出了所有產品項目。 從服務器fetch functionredux-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.log('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 您可以從這里訪問 state。

這是您需要進行的更改:

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>
        )}
      </>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM