反应redux并结合reducers

时间:2019-12-04 11:46:38

标签: javascript reactjs redux

您好,我正在使用thunk从后端获取数据 但是我不确定如何在我的联合减速器中做到这一点

我的类型:

export const FETCH_SUCESS = 'FETCH_SUCESS';
export const FETCH_FAIL = 'FETCH_FAIL';
export const FETCH_LOADING = 'FETCH_FAIL';
export const FILTER_PRODUCT = 'FILTER_PRODUCT';

我的动作

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

    const fetchSucess = data => ({
        type: FETCH_SUCESS,
        payload: {
          ...data
        }
      });

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

      const fetchFailed = error => ({
        type: FETCH_FAIL,
        payload: {
          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));
        });
    };
  };

我的减速机:

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

  const initialState = {
    loading: false,
    data: [],
    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,
          data: [...state.data, action.payload]
        };
      case FETCH_FAIL:
        return {
          ...state,
          loading: false,
          error: action.payload.error
        };
      default:
        return state;
    }
  }

我的组合器:

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

export default combineReducers({

});

我的商店:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

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

我的home.js

class HomeProducts extends Component {

    componentDidMount() {
        this.props.fetchData();
      }
    render() {
      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">
                {productItems}
            </div>  
            </div>
        )
    }
}
const mapStateToProps = (state) => {
        console.log(state);
  };
  const mapDispatchToProps = (dispatch) => {
    return {
        fetchData: () => dispatch(fetchProduct())
    };
  };
export default connect(mapStateToProps, mapDispatchToProps)(HomeProducts);

我怀疑在合并器中使用什么

获取日期和错误我如何加载,数据,错误

我不知道如何在菜单结合redux

中做到这一点

我也不知道我的actionreducer中是否有最佳实践

2 个答案:

答案 0 :(得分:1)

在您的合并器文件中,只需将减速器添加为键值对,如下所示:

if [[ $value = 200[0-9] || $value = 201[0-19] || $value = 202[0-1] ]]; then

理想情况下,您应该导入操作,然后通过connect方法将其传递给组件,这样您就可以作为道具从组件中访问它。

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

export default combineReducers({
    products: productReducer,
 // anotherState: anotherReducer
});

答案 1 :(得分:-1)

import thunkInject from 'redux-thunk-inject';

const mockStore = configureMockStore([thunkInject()]);
const store = mockStore(mockStore);
const wrapper = mount(<Provider store={store} />);
expect(wrapper).toMatchSnapshot();

要模拟使用thunk的商店,可以将其作为prop注入组件中。或在减速器中,例如

import productReducer from '../productReducer';

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

describe('product reducer', () => {
    it('Should handle FETCH_SUCCESS', () => {
        expect(productReducer(store, FETCH_SUCCESS)
        ).toEqual({
              loading: true
        });

        expect(productReducer(store, FETCH_FAIL).toEqual({
          loading: false,
          error: action.payload.error})
    });