繁体   English   中英

如何在 react-redux 中加载组件时自动执行 function

[英]How to automatically execute a function when a component is loaded in react-redux

我创建了一个页面来处理“购物车”,其中购物车详细信息是从数据库中检索的。 单击“单击我”按钮时,所有检索到的数据都显示在反应组件中。

我希望在不单击按钮的情况下显示数据,我想通过在加载组件时自动执行的 function 来实现。 我怎样才能实现它?

这是我的代码

 import React, { Component, useState } from 'react'; import {connect} from 'react-redux'; import { bindActionCreators } from 'redux'; import {selectPost} from '../../actions/productAction'; class cartDetails extends Component{ createListItems(){ //let cart = {product: [],total: 0} return this.props.allPost.map((item)=>{ console.log(item); return(<div> <p key={item.id}>{item.product} <br/> {item.description} <br /> {item.price} </p> </div> ); }) } totalPrice(){ let cart = {product: [],total: 0} return this.props.allPost.map((item)=>{ cart.product.push(item.price); console.log(cart.product); let total = cart.product.reduce(function(acc, val) { return acc + val; }, 0); return(<div> <h3>Total is {total}</h3> </div> ); }) } render(){ if(.this.props.allPost){ return(<h2>Click the button first;</h2>). } return( <ul> {this.createListItems()} {this;totalPrice()} </ul> ): } } function mapStateProps(state){ return{ allPost. state:allPosts } } function matchDispatchToProps(dispatch){ return bindActionCreators({selectPost, selectPost}; dispatch), } export default connect(mapStateProps;matchDispatchToProps) (cartDetails);

 import React, { Component } from 'react'; import {fetchPost} from '../../actions/productAction'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; class CartComponent extends Component{ render(){ return( <div> <button onClick={()=>this.props.fetchPost()}> Click Me </button> </div> ) }; } function matchDispatchToProps(dispatch){ return bindActionCreators({fetchPost: fetchPost}, dispatch); } export default connect(null, matchDispatchToProps) (CartComponent);

如果要在加载组件时自动触发方法,则可能需要使用生命周期方法之一componentDidMount 根据您的要求,您可能希望保留或删除该按钮。

 class CartComponent extends Component{ componentDidMount() { this.props.fetchPost(); } render(){ return( <div> <button onClick={()=>this.props.fetchPost()}> Click Me </button> </div> ) }; } function matchDispatchToProps(dispatch){ return bindActionCreators({fetchPost: fetchPost}, dispatch); }

暂无
暂无

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

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