简体   繁体   English

无法从商店获取更新的 state

[英]cannot get updated state from the store

#this is where I wanna do the Dispacth() action to props I believe I connected the component correctly. #这是我想对道具执行 Dispacth() 操作的地方,我相信我正确连接了组件。 the first argument maps state to props, the second maps to the dispatch.第一个参数将 state 映射到道具,第二个参数映射到调度。 So that when I dispatch the action then I log getState, I can see that the store is updated.因此,当我调度操作然后记录 getState 时,我可以看到存储已更新。

import React from "react";
import { Modal, Button } from "react-bootstrap";
import { connect } from "react-redux"


function AddCart(props) {

  console.log("AddCart Props", props);

  function handleClick(e) {
    e.preventDefault();
    props.addtocard()
    // props.addtocard((props.count * props.price))

  }

  return <Modal
    {...props}
    size="md"
    aria-labelledby="contained-modal-title-vcenter"
    centered
  >
    <Modal.Header closeButton
    >
      <Modal.Title id="contained-modal-title-vcenter">
        Successful!
          </Modal.Title>
    </Modal.Header>
    <Modal.Body>
      <p>
        <b>count:{props.count} size:{props.size}  x   title:{props.title} price:{(props.count * props.price).toFixed(2)}</b> added to your cart!
          </p>
    </Modal.Body>

    <Modal.Footer >
      <Button className="edit-btn" onClick={props.onHide}>Close</Button>
      <Button className="edit-btn" href="/cart" onClick={handleClick}>Go to Cart</Button>
    </Modal.Footer>
  </Modal>
}


function mapDispatchToProps(dispatch, props) {
  return {
    addtocard: () => dispatch({ type: "ADD_ITEM", price: (props.count * props.price) })
  }

}

export default connect(null, mapDispatchToProps)(AddCart);

#my reducer is below #我的减速机在下面

 const initState = {
        price: 35,
    
    
    }
    function cartReducer(state = initState, action) {
    
        switch (action.type) {
            case "ADD_ITEM":
                console.log("ITEMS ARE ADDED");
    
                return {
                    ...state,
                    price: action.price
                }
            default:
                return state;
        }
    }
    
    export default cartReducer;

#and this is where I wanna get the updated state to the props I believe I connected the component correctly. #这就是我想将更新的 state 更新到道具的地方,我相信我正确连接了组件。 the first argument maps state to props, the second maps to the dispatch.第一个参数将 state 映射到道具,第二个参数映射到调度。 So that when I dispatch the action then I log getState, I can see that the store is updated.因此,当我调度操作然后记录 getState 时,我可以看到存储已更新。

 import Navigation from "../Components/Navbar/Nav"
    import React, { Component } from 'react';
    import { Container } from 'react-bootstrap';
    import SubTotal from '../Components/Cart/Subtotal/Subtotal';
    import OrderOnlineSaving from '../Components/Cart/OnlineOrderSaving/OnlineOrderSaving';
    import TaxesFees from '../Components/Cart/TaxAndFees/TaxAndFees';
    import EstimatedTotal from '../Components/Cart/EstimatedTotal/EstimatedTotal';
    // import ItemDetails from './components/ItemDetails/ItemDetails';
    // import PromoCodeDiscount from './components/PromoCode/PromoCode';
    import '../Components/Cart/Cart.css'
    // Import redux provider
    import { connect } from 'react-redux';
    // import { handleChange } from '../actions/promoCodeActions';
    // import store from "../store"
    
    class Cart extends Component {
    
    
      constructor(props) {
        super(props);
    
        this.state = {
          total: parseFloat(props.stateItem.cartItem.price),
          taxes: 0,
          onlineOrderSavings: 0,
          estimatedTotal: 0,
          disablePromoButton: false
        };
      }
    
    
      componentDidMount = () => {
        this.setState(
          { taxes: (this.state.total + this.state.onlineOrderSavings) * 0.0875 },
          function () {
            this.setState({
              estimatedTotal:
                this.state.total + this.state.onlineOrderSavings + this.state.taxes
            });
          }
        );
      };
    
      giveDiscountHandler = () => {
        if (this.props.promoCode === 'DISCOUNT') {
          this.setState(
            { estimatedTotal: this.state.estimatedTotal * 0.9 },
            function () {
              this.setState({
                disablePromoButton: true
              });
            }
          );
        }
      };
    
      render() {
        console.log("cart props", this.props);
        return (
          <div className="main-cont">
            <Navigation />
            <Container className="purchase-card">
              <SubTotal price={this.state.total.toFixed(2)} />
              <OrderOnlineSaving price={this.state.onlineOrderSavings} />
              <TaxesFees taxes={this.state.taxes.toFixed(2)} />
              <hr />
              <EstimatedTotal price={this.state.estimatedTotal.toFixed(2)} />
            </Container>
          </div>
        );
      }
    }
    
    const mapStateToProps = (state, ownProps) => {
      return {
        stateItem: state
      }
    };
    
    export default connect(mapStateToProps)(Cart);

React props do not update until after a component has re-rendered.在组件重新渲染之前,React 道具不会更新。 If you trigger any state update, React or Redux, you cannot see new props values until sometime after your click handler has finished.如果您触发任何state 更新、React 或 Redux,则在单击处理程序完成后的某个时间之前,您无法看到新的 props 值。

So, this will never work as you're hoping for:所以,这永远不会像你希望的那样工作:

const onClick = () => {
  console.log(props.value); // original value
  props.updateSomeValue();
  console.log(props.value); // ERROR: This will _still_ be the original value!
}

If you're dispatching a Redux action and need to immediately access the updated state to run more logic, you should switch that code to execute in a Redux "thunk" function instead, which has access to getState() and can read the updated state as soon as the previous dispatch completes. If you're dispatching a Redux action and need to immediately access the updated state to run more logic, you should switch that code to execute in a Redux "thunk" function instead, which has access to getState() and can read the updated state上一次调度完成后。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM