简体   繁体   中英

How to transfer an image to another component using Redux?

I've set up my Redux to capture a user selection from a webshop (item, size, price) and send it to another Cart component. This is working perfectly, but I want to capture an image of the item and send it to Cart . Within each product page where you can add an item to the cart there is an image that I also would like to send with the user selection. This is an example of the product page component:

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);

This is my Cart component:

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);

In Cart I'm rendering the item selection data for each object added to the cart. Here is where I want to display the item image also.

Since I have a image slider set up, an example of one of the slides would be:

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

const SlideNocHOne= (props) => {

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

export default SlideNocHOne;

Let's say I want this DETAIL.png image on the Cart , how could I transfer it with the user selection using Redux?

These are my Redux components:

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
    }
};

How can I use my Redux setup to transfer the image of a user selection to Cart ?

If the path's of your components are relatively stable and you have a single location for the images, you can simply have a function that takes a component's displayName (in your example, Cart , etc.) and returns the relative path the image dir.

If you have that, you can just save a key/value collection in the reducer for what images each component should have, like:

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

When rending just use the mapper function which will provide you a relative path and that's it. Something like (or you can just map out that array):

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

Use require to fetch the image in the template like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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