[英]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.