javascript — невозможно получить состояние из метода mapstatetoprops

Невозможно получить состояние из метода mapstatetoprops

У меня есть код, как показано ниже. Мой вопрос касается реакции и избыточного использования. Я не могу получить состояние «категории» с помощью метода mapstate. Он показывает неопределенное, когда я пытаюсь утешить категории через this.props.categories в моем Product.js. Я приложил файл product.js, который имеет редуктор, а другой является моим основным компонентом Product.js.

Вот мой код Product.js:

 import React from 'react' import {connect} from 'react-redux' import withStyles from 'isomorphic-style-loader/lib/withStyles' import s from './Product.css' import { Select, Button, Table, Tooltip, InputNumber, Card} from 'antd' import ProductForm from './ProductForm' import {withCurrency} from '../../components' import debounce from 'lodash/debounce' import { changeSelectedProduct, getProducts, addProduct, changeMarkupFactor, updateProduct, currencyClicked, editRetailPrice, retailPriceUpdated, handleChange } from '../../reducers/product' const children = ["Home","Health","Beauty","Pregnancy","Kits","Animals","Travel","Cooking"] class Product extends React.Component { constructor(props) { super(props) this.getProducts = debounce(props.getProducts, 800); } componentWillMount() { // TODO get initial list of popular products this.props.getProducts() } handleChange = (values) ={amp}gt; { console.log(values) let Values = children.filter( (eachone,index) ={amp}gt;{ var includes = values.includes(`${index}`) if(includes){ return true } } ) this.props.handleChange(Values) } render() { const { products, loading, selectedProduct, onSubmit, formRef, markupFactor, changeMarkupFactor, changeSelectedProduct, currencies, totalPrice, currency, clearForms, addRetailPrice, currencyClicked, editRetailPrice, retailPriceUpdated, categories } = this.props; console.log('entire state', this.props.state) const columns = [ { key: 'name', dataIndex: 'name', width: 130, className: s.nameColumn, }, { key: 'price', dataIndex: 'price', className: s.priceColumn, render: (price, row) ={amp}gt; { if (row.id === 'retail-price' {amp}amp;{amp}amp; addRetailPrice) { return ( {amp}lt;InputNumber value={totalPrice.retail_price[currency.key]} onChange={(value) ={amp}gt; editRetailPrice(value, currency.key)} defaultValue={price[currency.key]} onBlur={() ={amp}gt; retailPriceUpdated(currency.key)} /{amp}gt; ); } return ( {amp}lt;Tooltip placement='topRight' title={ currencies.map(item ={amp}gt; currency.key !== item.key ? ( {amp}lt;div key={item.key}{amp}gt; {withCurrency(item, price[item.key])} {amp}lt;/div{amp}gt; ) : null ) } {amp}gt; {amp}lt;div onClick={() ={amp}gt; currencyClicked(row)}{amp}gt; {withCurrency(currency, price[currency.key])} {amp}lt;/div{amp}gt; {amp}lt;/Tooltip{amp}gt; ) } } ] let data = [] if (totalPrice) { data = [ {id:'receipe', name: 'Recipe', price: totalPrice.recipe.total_price}, {id:'container', name: 'Container', price: totalPrice.container.total_price}, {id:'wholesale-price', name: 'Wholesale Price', price: totalPrice.wholesale_price}, {id:'retail-price', name: 'Retail Price', price: totalPrice.retail_price}, ] } return ( {amp}lt;Card className={s.container} title={'Product'} bodyStyle={{minHeight: 409}} extra = {{amp}lt;a onClick={clearForms}{amp}gt;{'Clear'}{amp}lt;/a{amp}gt;} {amp}gt; {/* {amp}lt;div className={s.container}{amp}gt; */} {/* {amp}lt;div className={s.headerWrapper}{amp}gt; {amp}lt;h3 className={s.header}{amp}gt;{'Product'}{amp}lt;/h3{amp}gt; */} {/*use clear here below */} {/* {amp}lt;a onClick={clearForms}{amp}gt;{'Clear'}{amp}lt;/a{amp}gt; {amp}lt;/div{amp}gt; */} {amp}lt;div className={s.containerSearchWrapper}{amp}gt; {amp}lt;Select className = {s.search} showSearch allowClear value={selectedProduct ? `${selectedProduct.id}` : undefined} className={s.productSearch} placeholder='Search' notFoundContent={loading.products ? {amp}lt;Spin size='small'/{amp}gt; : null} filterOption={false} onSearch={(search) ={amp}gt; this.getProducts({search})} onChange={(id) ={amp}gt; { const newProduct = products.find(item ={amp}gt; item.id ===  id) changeSelectedProduct(newProduct) }} {amp}gt; {products.map(item ={amp}gt; {amp}lt;Select.Option key={item.id}{amp}gt;{item.name}{amp}lt;/Select.Option{amp}gt; )} {amp}lt;/Select{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;ProductForm markupFactor={markupFactor} changeMarkupFactor={changeMarkupFactor} ref={formRef} children={children} handleChange={this.handleChange} /{amp}gt; {amp}lt;Table className={s.table} columns={columns} dataSource={data} loading={loading.totalPrice} size='small' rowKey={(record, i) ={amp}gt; i} pagination={false} showHeader={false} locale={{emptyText: 'Total price'}} /{amp}gt; {amp}lt;div className={s.actions}{amp}gt; {amp}lt;Button onClick={() ={amp}gt; onSubmit('update')} loading={loading.updatingProduct} disabled={!selectedProduct} {amp}gt; {'Save'} {amp}lt;/Button{amp}gt; {amp}lt;Button onClick={() ={amp}gt; onSubmit('add')} loading={loading.addingProduct} {amp}gt; {'Create new'} {amp}lt;/Button{amp}gt; {amp}lt;/div{amp}gt; {/* {amp}lt;/div{amp}gt; */} {amp}lt;/Card{amp}gt; ) } } const mapState = state ={amp}gt; ({ ...state.product, currency: state.global.currency, currencies: state.global.currencies, categories: state.global.categories, }) const mapDispatch = { getProducts, addProduct, updateProduct, changeMarkupFactor, changeSelectedProduct, currencyClicked, editRetailPrice, retailPriceUpdated, handleChange, } export default connect(mapState, mapDispatch)(withStyles(s)(Product)) 

Вот мой код product.js

 import createReducer, {RESET_STORE} from '../createReducer' import {getToken} from './user' import qs from 'query-string' import _ from 'lodash'; import {message} from 'antd' import messages from '../messages' import {getFieldValue} from '../utils' // ------------------------------------ // Constants // ------------------------------------ export const GET_PRODUCT_REQUEST = 'Product.GET_PRODUCT_REQUEST' export const GET_PRODUCT_SUCCESS = 'Product.GET_PRODUCT_SUCCESS' export const GET_PRODUCT_FAILURE = 'Product.GET_PRODUCT_FAILURE' export const ADD_PRODUCT_REQUEST = 'Product.ADD_PRODUCT_REQUEST' export const ADD_PRODUCT_SUCCESS = 'Product.ADD_PRODUCT_SUCCESS' export const ADD_PRODUCT_FAILURE = 'Product.ADD_PRODUCT_FAILURE' export const UPDATE_PRODUCT_REQUEST = 'Product.UPDATE_PRODUCT_REQUEST' export const UPDATE_PRODUCT_SUCCESS = 'Product.UPDATE_PRODUCT_SUCCESS' export const UPDATE_PRODUCT_FAILURE = 'Product.UPDATE_PRODUCT_FAILURE' export const GET_TOTAL_PRICE_REQUEST = 'Product.GET_TOTAL_PRICE_REQUEST' export const GET_TOTAL_PRICE_SUCCESS = 'Product.GET_TOTAL_PRICE_SUCCESS' export const GET_TOTAL_PRICE_FAILURE = 'Product.GET_TOTAL_PRICE_FAILURE' export const CHANGE_SELECTED_PRODUCT = 'Product.CHANGE_SELECTED_PRODUCT' export const CHANGE_MARKUP_FACTOR = 'Product.CHANGE_MARKUP_FACTOR' export const CHANGE_RETAIL_PRICE = 'Product.CHANGE_RETAIL_PRICE'; export const EDITING_RETAIL_PRICE = 'Product.EDITING_RETAIL_PRICE'; export const RETAIL_PRICE_UPDATED = 'Product.RETAIL_PRICE_UPDATED'; export const CLEAR = 'Product.CLEAR' export const ADD_CATEGORIES = 'Product.ADD_CATEGORIES' // ------------------------------------ // Actions // ------------------------------------ // ------------------------------------ // Actions // ------------------------------------ export const changeSelectedProduct = (selectedProduct) ={amp}gt; (dispatch, getState) ={amp}gt; { dispatch({type: CHANGE_SELECTED_PRODUCT, selectedProduct}) // dispatch(changeSelectedComponents(selectedProduct ? selectedProduct.components : [])) } export const currencyClicked = (row) ={amp}gt; (dispatch) ={amp}gt; { if (!row.id === 'retail-price') return; dispatch({type: CHANGE_RETAIL_PRICE}) } export const editRetailPrice = (value, currencyKey) ={amp}gt; (dispatch, getState) ={amp}gt; { const { totalPrice } = getState().product; totalPrice.retail_price[currencyKey] = value; dispatch({type: EDITING_RETAIL_PRICE, totalPrice}); } export const retailPriceUpdated = (currencyKey) ={amp}gt; (dispatch, getState) ={amp}gt; { const { totalPrice } = getState().product; const markupFactor = parseFloat(totalPrice.retail_price[currencyKey] / totalPrice.wholesale_price[currencyKey]).toFixed(2); dispatch({type: RETAIL_PRICE_UPDATED, totalPrice}); dispatch({type: CHANGE_MARKUP_FACTOR, markupFactor}); } export const getProducts = (params = {}) ={amp}gt; (dispatch, getState, {fetch}) ={amp}gt; { dispatch({type: GET_PRODUCT_REQUEST, params}) const {token} = dispatch(getToken()) const {search, ordering} = getState().product return fetch(`/pands/products/?${qs.stringify({ search, ordering, })}`, { method: 'GET', token, success: (res) ={amp}gt; dispatch({type: GET_PRODUCT_SUCCESS, res}), failure: (err) ={amp}gt; dispatch({type: GET_PRODUCT_FAILURE}), }) } export const addProduct = (values) ={amp}gt; (dispatch, getState, {fetch}) ={amp}gt; { dispatch({type: ADD_PRODUCT_REQUEST}) const {token} = dispatch(getToken()) const {currencies} = getState().global const {selectedRecipe} = getState().recipe const {selectedContainer} = getState().container return fetch(`/pands/products/`, { method: 'POST', body: { ...values, recipe: selectedRecipe.id, container: selectedContainer.id, currencies: currencies.map(item ={amp}gt; item.key), }, token, success: (selectedProduct) ={amp}gt; { dispatch({type: ADD_PRODUCT_SUCCESS, selectedProduct}) message.success(messages.addProductSuccess) }, failure: (err) ={amp}gt; { dispatch({type: ADD_PRODUCT_FAILURE}) message.error(messages.addProductError) }, }) } export const updateProduct = (values) ={amp}gt; (dispatch, getState, {fetch}) ={amp}gt; { dispatch({type: UPDATE_PRODUCT_REQUEST}) const {token} = dispatch(getToken()) const {currencies} = getState().global const {selectedProduct} = getState().product const {selectedRecipe} = getState().recipe const {selectedContainer} = getState().container return fetch(`/pands/products/${selectedProduct.id}/`, { method: 'PATCH', body: { ...values, recipe: selectedRecipe.id, container: selectedContainer.id, currencies: currencies.map(item ={amp}gt; item.key), }, token, success: (selectedProduct) ={amp}gt; { dispatch({type: UPDATE_PRODUCT_SUCCESS, selectedProduct}) message.success(messages.updateProductSuccess) }, failure: (err) ={amp}gt; { dispatch({type: UPDATE_PRODUCT_FAILURE}) message.error(messages.updateProductError) }, }) } export const getTotalPrice = () ={amp}gt; (dispatch, getState, {fetch}) ={amp}gt; { const {token} = dispatch(getToken()) dispatch({type: GET_TOTAL_PRICE_REQUEST}) const {currencies} = getState().global const {markupFactor} = getState().product const {fields: {ingredients}} = getState().rawMaterials const {fields: {components}} = getState().components return fetch(`/pands/products/calculate/`, { method: 'POST', token, body: { recipe: { ingredients: getFieldValue(ingredients), }, container: { components: getFieldValue(components), }, markup_factor:  markupFactor, currencies: currencies.map(item ={amp}gt; item.key), }, success: (totalPrice) ={amp}gt; dispatch({type: GET_TOTAL_PRICE_SUCCESS, totalPrice}), failure: (error) ={amp}gt; dispatch({type: GET_TOTAL_PRICE_FAILURE, error}), }) } export const changeMarkupFactor = (markupFactor) ={amp}gt; (dispatch, getState) ={amp}gt; { dispatch({type: CHANGE_MARKUP_FACTOR, markupFactor}) dispatch(getTotalPrice()) } export const clear = () ={amp}gt; ({type: CLEAR}) // ----------------------------------- export const handleChange = (values) ={amp}gt; (dispatch) ={amp}gt; { dispatch({type: ADD_CATEGORIES,values}); } // ------------------------------------ // Reducer // ----------------------------------- const initialState = { loading: { products: false, addingProduct: false, updatingProduct: false, totalPrice: false, }, products: [], selectedProduct: null, error: null, totalPrice: null, markupFactor: 1.3, addRetailPrice: false, categories:[], } export default createReducer(initialState, { [GET_PRODUCT_REQUEST]: (state, {params}) ={amp}gt; ({ search: _.has(params, 'search') ? params.search : state.search, ordering: params.sorter ? `${params.sorter.order === 'descend' ? '-' : ''}${params.sorter.field}` : state.ordering, filters: params.filters || state.filters, loading: { ...state.loading, products: false, }, }), [GET_PRODUCT_SUCCESS]: (state, {res: {results}}) ={amp}gt; ({ products: results, loading: false, }), [GET_PRODUCT_FAILURE]: (state, action) ={amp}gt; ({ loading: false, }), [ADD_PRODUCT_REQUEST]: (state, action) ={amp}gt; ({ loading: { ...state.loading, addingProduct: true, }, }), [ADD_PRODUCT_SUCCESS]: (state, {selectedProduct}) ={amp}gt; ({ selectedProduct, loading: { ...state.loading, addingProduct: false, }, }), [ADD_PRODUCT_FAILURE]: (state, action) ={amp}gt; ({ loading: { ...state.loading, addingProduct: false, }, }), [UPDATE_PRODUCT_REQUEST]: (state, action) ={amp}gt; ({ loading: { ...state.loading, updatingProduct: true, }, }), [UPDATE_PRODUCT_SUCCESS]: (state, {selectedProduct}) ={amp}gt; ({ selectedProduct, loading: { ...state.loading, updatingProduct: false, }, }), [UPDATE_PRODUCT_FAILURE]: (state, action) ={amp}gt; ({ loading: { ...state.loading, updatingProduct: false, }, }), [GET_TOTAL_PRICE_REQUEST]: (state, action) ={amp}gt; ({ totalPrice: null, loading: { ...state.loading, totalPrice: true, }, }), [GET_TOTAL_PRICE_SUCCESS]: (state, {totalPrice}) ={amp}gt; ({ totalPrice, loading: { ...state.loading, totalPrice: false, } }), [EDITING_RETAIL_PRICE]: (state, {totalPrice}) ={amp}gt; ({ totalPrice }), [RETAIL_PRICE_UPDATED]: (state, {totalPrice}) ={amp}gt; ({ totalPrice, addRetailPrice: false }), [GET_TOTAL_PRICE_FAILURE]: (state, {error}) ={amp}gt; ({ error, loading: { ...state.loading, totalPrice: false, }, }), [CHANGE_MARKUP_FACTOR]: (state, {markupFactor}) ={amp}gt; ({ markupFactor, }), [CHANGE_SELECTED_PRODUCT]: (state, {selectedProduct}) ={amp}gt; ({ selectedProduct, }), [CHANGE_RETAIL_PRICE]: (state) ={amp}gt; ({ addRetailPrice: true, }), [ADD_CATEGORIES]: (state,{ categories }) ={amp}gt; ({ categories }), [CLEAR]: (state, action) ={amp}gt; RESET_STORE, }) 
Понравилась статья? Поделиться с друзьями:
JavaScript & TypeScript
Adblock
detector