简体   繁体   English

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

[英]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. 我已经设置了Redux以从网上商店捕获用户选择(项目,大小,价格),并将其发送到另一个Cart组件。 This is working perfectly, but I want to capture an image of the item and send it to Cart . 这可以正常工作,但是我想捕获项目的图像并将其发送到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: 这是我的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);

In Cart I'm rendering the item selection data for each object added to the cart. 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? 假设我要把这个DETAIL.png图片放到Cart DETAIL.png ,如何通过Redux与用户选择一起转移它?

These are my Redux components: 这些是我的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
    }
};

How can I use my Redux setup to transfer the image of a user selection to Cart ? 如何使用Redux设置将用户选择的图像传输到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. 如果组件的路径相对稳定,并且图像具有单个位置,则可以简单地使用一个函数,该函数采用组件的displayName (在您的示例中为Cart等),然后将相对路径返回图像目录。

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. 租用时,只需使用mapper函数即可,这将为您提供相对路径。 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: 使用require来获取模板中的图像,例如:

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

暂无
暂无

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

相关问题 如何使用Redux将用户选择转移到另一个组件? - How to use Redux to transfer a user selection to another component? 是否可以通过HOC中的react-redux将带有数据的数组传输到另一个组件 - Is it possible to transfer array with data to another component by react-redux in HOC 如何使用Redux获取另一个组件的本地状态 - How to get local state of another component using Redux 如何使用路由器/路由器参数将数据从一个父组件传输到另一个父组件 - How to transfer data from one parent component to another parent component in react using router / router params 如何将数据传输/填充到 nextJS 中的另一个组件 - How to transfer/populate a data to another component in nextJS 如何将 state 从一个组件转移到另一个? - How to transfer a state from a component to another? 在反应组件中,一旦使用 redux 从另一个组件更改状态,如何从状态中获取最新数据? - In a react components, how to get latest data from state once it is changed from another component using redux? 我如何从另一个不是反应组件的文件中调用 useReducer 调度 function? (不使用 Redux) - How do i call a useReducer dispatch function from another file, which is not a react component? (without using Redux) 我如何使用带有 redux 和 react.js 的按钮将数据从一个组件传递到另一个组件? - How can i pass the data from one Component to another using a button with redux and react.js? 我们如何在不使用Angular 2中的参数,查询参数和服务的情况下将数据对象从一个组件传输到另一组件 - How can we transfer data object from one component to another component without using params, queryparams and services in Angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM