繁体   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