javascript - 在 React-Redux 应用程序中访问另一个组件中的 Connect 函数值时出现问题

标签 javascript reactjs redux react-redux

我已经在我的 React 应用程序中设置了 Redux,但是当我使用 this.props 访问单独文件中另一个组件中的数据时,我没有得到任何数据传递。我的 Action 正在执行,它传递了我想要的数据。 这是我的 actions.js:

export const ADD_CART = 'ADD_CART';

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

我的 reducer.js 是:

import {ADD_CART} from './actions';

export default Reducer;

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

我的 action creator 包含 cart,这是我想传递给组件的内容:

...
class WebShop extends Component {
    ...

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

   ...


    render() {
        return (
            ..
}

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

function mapStateToProps(state) {
   return {
      cartItem: state.reducer,
   }
}

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);

当我尝试访问另一个文件和组件中的 cart 时:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default class Cart extends Component {
    render() {
        console.log(this.props.cart);
        return(
            <div className= "Webcart" id="Webcart"></div>
        );
    }
}

这是我的 store.js:

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


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

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

我的 Provider 在我的 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 About from 'views/About';
import Cart from 'views/webcart';


console.log(store);
ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Home } />
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
            </Route>
        </Router>
    </Provider>,    
    document.getElementById('app') // eslint-disable-line
);

在更新我的代码以使用 mapStateToProps 之后,我现在收到错误 Uncaught TypeError: Cannot read property 'Reducer' of undefined。如果 Reducer 应该由 API 访问,为什么我会得到这个?

最佳答案

所以我看到了你的 pastebin 和你的评论,我觉得你是如此接近,尤其是@Faaiz 的回答(所以阅读这个答案与@Faaiz 的商店、initialState 和 reducer 响应一致)。所以让我们回滚它:

假设您有两个组件(WebShop 和 Cart);并且您想与这些组件共享一个全局状态(购物车)。这些方法中的任何一种都有效:

  1. “连接组件”的嵌套组件 - 例如 <Cart /><WebShop /> 的 child 它连接(通过 redux 与 mapStateToProps 等连接)到全局状态。然后在 WebShop 中,您可以执行以下操作:

    import { addCart } from './actions';
    import { connect } from 'react-redux';
    // other imports    
    class WebShop extends Component {
      ...//
      handleClick() {
        const cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
      } 
      render() {
        return (
          ...//
          <Cart cart={this.props.cart} />
        )
      }
    }
    // for completeness I brought the mapStateToProps
    function mapStateToProps(state) {
      return { cart: state.cart };
    }
    
    const mapDispatchToProps = (dispatch) => {
      return {
        onCartAdd: (item) => {
          dispatch(addCart(item));
        }
      }
    }
    export default connect(mapStateToProps, mapDispatchToProps)(WebShop);
    

在您的 cart.js 文件中,您可以:

    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }
  1. 两个单独的“连接组件”——这意味着将两个组件(通过 redux 连接与 mapStateToProps 等)连接到全局状态。因此,您的购物车和网上商店在这方面将是相似的,如下所示:

    class WebShop extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...// Other stuffs 
        )
      }
    }
    // for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
    function mapStateToProps(state) {
      return { cart: state.cart };
    }
    export default connect(mapStateToProps, mapDispatchToProps)(WebShop);
    

cart.js 文件看起来像这样:

    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }
    // for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
    function mapStateToProps(state) {
      return { cart: state.cart };
    }
    export default connect(mapStateToProps, mapDispatchToProps)(Cart);

注意 我宁愿设置你的 addCart行动待addItemToCart和你的全局状态 cart现在将是一个项目数组。您的 reducer.js 看起来类似于:

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

function Reducer(state = initialState, action){
  switch(action.type){
    case ADD_CART:
      return {
          ...state,
          cart: state.cart.push(action.payload)
      };
    default:
      return state;
  };
}

和你的handleClick()看起来像

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

但是请随意使用您的用例,我的意见可能完全不对。

希望对您有所帮助。

关于javascript - 在 React-Redux 应用程序中访问另一个组件中的 Connect 函数值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233546/

相关文章:

javascript - 在 Materialise Calendar 中设置年份范围

javascript - 限制 HTML 输入只允许粘贴

javascript - 如何使用 angularjs 过滤器从字符串中删除制表符 (\t)?

html - Redux 是存储 JWT token 的安全场所吗?

javascript - 单元测试 Redux 操作 - Thunk Undefined

javascript - 试图理解 nodejs 文档。如何发现回调参数

javascript - ASP.NET Javascript 服务服务器端渲染特定路由

javascript - 在React JS中显示单击时隐藏的内容

reactjs - React、material-ui 和步进器 : how to display html in each steps

javascript - 使用 enzyme 进行 React/Redux 测试