简体   繁体   English

React redux mapStateToProps 未设置返回到我的道具

[英]React redux mapStateToProps not set return to my props

Problem when using prop, it starts as null and then I use map but as it is null returns an error.使用 prop 时出现问题,它从null开始,然后我使用map但因为它是null返回错误。

And then ends up not responding to the updated state:然后最终没有响应更新的状态:

class HomeProducts extends Component {

    componentDidMount() {
        this.props.fetchProduct();
      }
    render() {
        console.log(this.props)

      const productItems = this.props.products.map( product => (
          <div className="col-md-4 pt-4 pl-2">
          <div className = "thumbnail text-center"> 
          <a href={`#${product.id}`}  onClick={(e)=>this.props.handleAddToCard(e,product)}>
              <p>
                  {product.name}
              </p>
          </a>
          </div>
              <b>{util.formatCurrency(product.price)}</b>
              <button className="btn btn-primary" onClick={(e)=>this.props.handleAddToCard(e,product)}>Add to Cart</button>
          </div>
      )
      )
        return (
            <div className="container">
            <div className="row">

            </div>  
            </div>
        )
    }
}
const mapStateToProps = (state) => {
    console.log(state);
    return{
        products: state.data.products,
        loading: state.data.loading,
        error: state.data.error
    }
  };
  const mapActionsToProps = {
    fetchProduct: fetchProduct
};
export default connect(mapStateToProps, mapActionsToProps)(HomeProducts);

my reducer:我的减速机:

import {
    FETCH_SUCESS,
    FETCH_FAIL,
    FETCH_LOADING,
  } from '../constants/fetchTypes';

  const initialState = {
    loading: false,
    products: [],
    error: null
  };

  export default function productReducer(state = initialState, action) {

    switch (action.type) {
      case FETCH_LOADING:
        return {
          ...state,
          loading: true
        };
      case FETCH_SUCESS:
        return {
          ...state,
          loading: false,
          error: null,
          ...state, products: action.data
        };
      case FETCH_FAIL:
        return {
          ...state,
          loading: false,
          error: action.error
        };
      default:
        return state;
    }
  }

my action:我的行动:

import api from '../../services/api';
import {FETCH_SUCESS,FETCH_FAIL,FETCH_LOADING} from '../constants/fetchTypes';

const fetchSucess = data => ({
    type: FETCH_SUCESS,
    data

  });

  const fetchStarted = () => ({
    type: FETCH_LOADING
  });

  const fetchFailed = error => ({
    type: FETCH_FAIL, 
      error
  });

  export const fetchProduct = () => {
      console.log('action')
    return dispatch => {
      dispatch(fetchStarted());

      api
        .get('/products')
        .then(res => {
          dispatch(fetchSucess(res.data));
        })
        .catch(err => {
          dispatch(fetchFailed(err.message));
        });
    };
  };

my combiner reducer:我的合路器减速器:

import { combineReducers } from 'redux'
import  productReducer from './productsFetch.reducer';

export default combineReducers({
    data: productReducer 
});

my store:我的店铺:

export default function configureStore(initialState) {
    return createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk)
    );
}

And I got:我得到了:

Cannot read property 'map' of undefined无法读取未定义的属性“地图”

Can you try like this without using initialState in createStore?你能在不使用 createStore 中的 initialState 的情况下尝试这样吗?

  return createStore(
        rootReducer,
        applyMiddleware(thunk)
    );

It seems that when we try to initialize the state both in createStore and reducer, something is broken.似乎当我们尝试在 createStore 和 reducer 中初始化状态时,某些东西被破坏了。

Docs 文档

It seems you need to check the initialState in your reducer, and see if you actually have an empty array for products .看来您需要检查您的减速器中的initialState ,看看您是否真的有一个用于products的空数组。 With that you do not have to deal with the cases where is empty in the very first load.这样您就不必处理在第一次加载时为空的情况。 So when having the initialState with [] , then you could also play around with different messages for the user, like (if array is empty, then either show LOADING (for cases when you also handle that state in your reducer) or EMPTY list when you actually finished loading the data.因此,当使用[]的 initialState 时,您还可以为用户处理不同的消息,例如(如果数组为空,则显示 LOADING(对于您还在减速器中处理该状态的情况)或 EMPTY 列表,当你实际上完成了数据的加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM