如何在我的Reducer for React Redux应用程序中设置返回的内容?

时间:2017-05-27 15:32:33

标签: javascript reactjs redux react-redux

我在React环境中设置Redux,以便能够在组件之间移动用户选择数据。我希望能够获得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() {
        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值并使用Redux将其移动到其他组件。这是我的Redux store.js

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


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

const store = createStore(
  reducer,
  applyMiddleware(
    createLogger(),
    thunkMiddleware
  )
);
export default store; 

这是我的actions.js

export const ADD_CART = 'ADD_CART';

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

和我的reducers.js

import {ADD_CART} from './actions';

export default reducer;

function rootReducer(state, action){
    switch(action.type)
        case ADD_CART:
            return  
}

要将我的商店与我的组件相关联,我将所有组件都包含在<Provider>的{​​{1}}标记内:

app.js

如何设置我的reducer中返回的内容,以便将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='Webshop' component={ Webshop } /> <Route path='Cart' component={ Cart } /> </Route> </Provider> </Router>, document.getElementById('app') // eslint-disable-line ); 传递给我的应用中的其他组件?

2 个答案:

答案 0 :(得分:0)

使用来自&#39; react-redux&#39;的addCart来连接您的connect组件并给它一个onCartAdd道具,将addCart行动发送到您的商店。

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

import Shirt from './shirt.jpg';

class WebShop extends Component {
  ...

  handleClick() {
    let cart = {price:0,item:"userselection",size:this.state.value};
    this.props.onCartAdd(cart);
  }

  ...
}

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

export deafult connect(null, mapDispatchToProps)(WebShop);
你的&#39; actions.js&#39;中的

addCart需要以item为参数:

export const ADD_CART = 'ADD_CART';

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

Usage with React更详细地解释了如何自定义mapDispatchToProps

答案 1 :(得分:0)

应将多个组件使用的应用数据添加到store。然后,您可以使用connect

从任何组件访问此数据

如果您希望其他组件访问cart,则应将其添加到商店中,

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

然后您可以使用connect在任何组件中使用此值。

在您的root reducer中,在分派操作时更改此值

import {ADD_CART} from './actions';

export default reducer;

function rootReducer(state, action){
    switch(action.type)
        case ADD_CART:
            return {
             ...state,
             cart: action.payload
             }
}