我想使用Redux将商品(商品,尺寸和价格)选项从商品列表转移到单独的购物车组件。我设法在我的环境中设置了Redux,但无法弄清楚如何使用它来获取这些数据。这是我的app.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';
import App from 'views/App';
import Home from 'views/Home';
import Webshop from 'views/webshop';
import Cart from 'views/webcart';
ReactDOM.render(
<Router history={ hashHistory }>
<Provider store={store}>
<Route path='/' component={ App }>
<IndexRoute component={ Home } />
<Route path='about' component={ Webshop } />
<Route path='Cart' component={ Cart } />
</Route>
</Provider>
</Router>,
document.getElementById('app') // eslint-disable-line
);
我相信我已将我的组件正确包装在Redux Provider
标记中,这些标记将链接我的Redux store.js
,如下所示:
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';
var initialState = {
data: [],
url: "/api/comments",
pollInterval: 2000
}
const store = createStore(
applyMiddleware(
createLogger(),
thunkMiddleware
)
);
export default store;
我尝试传递的值cart
在webshop.js
文件中,如下所示:
import React, { Component } from 'react';
import{ Connect } from 'react-redux';
import Shirt from './shirt.jpg';
export default class addCart extends Component {
constructor(){
super();
this.state = {value: 'medium'}
this.handleClick = this.handleClick.bind(this);
this.change = this.change.bind(this);
}
handleClick() {
console.log(this.state);
let cart = {price:0,item:"userselection",size:this.state.value};
console.log(cart);
}
change(e){
this.setState({value: e.target.value})
}
itemSelection(){
let userOrder = {price:0,item:"",size:""};
let userItem = "";
if (userItem == "shirt1") {
let itemPrice = 20.00;
}
}
render() {
return (
<div className='Webshop' id='Webshop'>
<li id="Productlist">
<div className='Product'>
<img src={Shirt}></img>
<button onClick={this.handleClick} className="addit">Add to cart</button>
<select id="size" 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>
</div>
<div className='Product'>
<img src={Shirt}></img>
<button onClick={this.handleClick} className="addit">Add to cart</button>
<select id="size" 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>
</div>
</li>
</div>
);
}
}
如何从用户的选择中获取此cart
值并将其传递到单独文件中的另一个组件?
答案 0 :(得分:1)
有几种方法可以将cart
传递给另一个组件(WebCart)。
一般步骤是:
connect
将webCart容器连接到商店
说实话,你的代码什么也没做,因为一切看起来像硬编码你需要阅读一点redux并发布更多代码