簡體   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