如何使用Redux将图像传输到另一个组件?

时间:2017-08-08 01:47:07

标签: javascript html reactjs redux

我已经设置了我的Redux以从网上商店(项目,大小,价格)捕获用户选择并将其发送到另一个Cart组件。这是完美的,但我想捕获项目的图像并将其发送到Cart。在每个产品页面中,您可以将项目添加到购物车,我还希望通过用户选择发送图像。这是产品页面组件的示例:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addCart } from '../../actions';

import SeltzShirt from './seltzshirt.jpg';
import Slideone from './slideSeltzOne';
import Slidetwo from './slideSeltzTwo';
import RightArrow from './rightarrow';
import LeftArrow from './leftarrow';

export class ProductPage3 extends  Component {

    constructor(props) {
        super(props);
        this.state = {
            slideCount: 1, 
            value: 'medium', cartData: {}   
        }

        this.nextSlide = this.nextSlide.bind(this);
        this.previousSlide = this.previousSlide.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
    }

    handleClick() {
        let cart = {price:25,item:this.description.innerHTML,size:this.state.value};
        this.props.onCartAdd(cart);
        console.log(cart);
        this.itemSelection(cart);
    } 

    ...

    componentDidMount () {
        window.scrollTo(0, 0)
    }

    render() {
        return (
            <div className= "ProductPage" id="ProductPage">
                <div id='slider'>
                    {this.state.slideCount === 1 ? <Slideone /> : null}
                    {this.state.slideCount === 2 ? <Slidetwo /> : null}

                    <RightArrow nextSlide={this.nextSlide} />
                    <LeftArrow previousSlide={this.previousSlide} />

                </div>
                <div id='InfoSquare'>
                    <div id='wrapper'>
                        <div id='item' ref={i=>this.description=i}>LOGO TEE</div>
                        <div id='description'>Black tee 100% cotton with red silkscreened logo on front and back.</div>
                        <select id="size2" onChange={this.change} value={this.state.value}>
                            <option value="medium">Medium</option>
                            <option value="large">Large</option>
                            <option value="x-large">X-large</option>
                        </select>
                        <button onClick={this.handleClick} className="addit">ADD TO CART</button>
                    </div>

                </div>
            </div>   
        );
    }

     nextSlide() {
      this.setState({ slideCount: this.state.slideCount + 1 })
    }

    previousSlide() {
      this.setState({ slideCount: this.state.slideCount - 1 })
    }

}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
   return {
      cart: state.cart
   };
}

export default connect(mapStateToProps,mapDispatchToProps)(ProductPage3);

这是我的Cart组件:

import React, { Component } from 'react';
import {addCart} from './Shop';
import { removeCart } from '../../actions'; 
import { connect } from 'react-redux';

export class Cart extends Component {
    constructor(props) {
        super(props);
        this.state = {items: this.props.cart,cart: [],total: 0};
    }

    ...

    render() {
        return(
            <div className= "Webcart" id="Webcart">
                <div id='WebcartWrapper'>
                    <ul id='webCartList'>
                        {this.state.items.map((item, index) => {
                            return <li className='cartItems' key={'cartItems_'+index}>
                                <h4>{item.item}</h4>
                                <p>Size: {item.size}</p>
                                <p>Price: {item.price}</p>
                                <button onClick={() => this.handleClick(item)}>Remove</button>
                            </li>
                        })}
                    </ul>
                    <div>Total: ${this.countTotal()}</div>
                </div>
            </div>
        );
    }
}



const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
        onCartRemove: (item) => {
            dispatch(removeCart(item));
        },
    }
}

function mapStateToProps(state) {
  return { cart: state.cart };
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

Cart我正在为添加到购物车的每个对象呈现项目选择数据。这里也是我想要显示项目图像的地方。

由于我设置了一个图像滑块,其中一个幻灯片的示例如下:

import React, { Component } from 'react';
import take1 from './DETAIL.png';

const SlideNocHOne= (props) => {

    return <img src= {take1} id="slide"></img>
}

export default SlideNocHOne;

假设我想在DETAIL.png上显示这个Cart图片,如何使用Redux将其与用户选择一起传输?

这些是我的Redux组件:

import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import  reducer  from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';


const store = createStore(
  reducer,
  undefined,
  compose(
    applyMiddleware(createLogger(), thunkMiddleware),
    autoRehydrate()
  )
);

persistStore(store, {whitelist: ['cart']});

export default store; 

import {ADD_CART} from './actions';
import {REMOVE_CART} from './actions';
import { REHYDRATE } from 'redux-persist/constants';

export default Reducer;

var initialState = {
  cart:{},
  data: [],
  url: "/api/comments",
  pollInterval: 2000
};

function Reducer(state = initialState, action){
    switch(action.type){
        case REHYDRATE:
                if (action.payload && action.payload.cart) {
                    return { ...state, ...action.payload.cart };
                }
            return state;

            case ADD_CART:
                return {
                    ...state,
                    cart: [...state.cart, action.payload]
                }

            case REMOVE_CART:
                return {
                    ...state,
                    cart: state.cart.filter((item) => action.payload !== item)
                }



            default:
                return state; 
    };
}

export const ADD_CART = 'ADD_CART';
export const REMOVE_CART = 'REMOVE_CART';

export function addCart(item){
    return {
        type: ADD_CART,
        payload: item
    }
};

export function removeCart(item){
    return{
        type:REMOVE_CART,
        payload: item
    }
};

如何使用我的Redux设置将用户选择的图像传输到Cart

1 个答案:

答案 0 :(得分:0)

如果组件的路径相对稳定且图像只有一个位置,则可以使用一个带有组件displayName的函数(在您的示例中为Cart等)。 )并返回图像目录的相对路径。

如果你有这个,你可以在减速器中保存一个键/值集合,以获得每个组件应该具有的图像,例如:

{
    CartComponent: ['DETAIL.png', 'DETAIL_2.png']
    ...
}

当rending只使用mapper函数时,它会为你提供一个相对路径,就是这样。类似的东西(或者你可以只绘制出那个数组):

const relativeImagePath = getRelativeImageDirPathByCompName('CartComponent') + this.props.images.CartComponent[0];

使用require获取模板中的图片,如:

<img src={require(relativeImagePath)} alt="Something"/>