无法从商店获取更新状态

时间:2020-08-05 19:32:59

标签: javascript reactjs redux

#这是我想对道具执行Dispacth()动作的地方 我相信我正确连接了组件。第一个参数将状态映射到道具,第二个参数将映射到调度。这样,当我分派操作然后登录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减速器在下面

 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;

#这是我想要获取道具的更新状态的地方 我相信我正确连接了组件。第一个参数将状态映射到道具,第二个参数将映射到调度。这样,当我分派操作然后登录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);

1 个答案:

答案 0 :(得分:1)

在重新渲染组件之前,反应道具不会更新。如果您触发任何状态更新,React或Redux,则您的 直到点击处理程序完成后的某个时间才能看到新的道具值。

因此,这永远不会如您所愿:

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

如果您要调度Redux操作,并且需要立即访问更新后的状态以运行更多逻辑,则应该切换该代码以在Redux“ thunk”函数中执行,该函数可以访问getState()和先前的调度完成后,便可以读取更新的状态。