每次进行交易时,我都需要更新硬币数量,这些硬币位于模板组件中的,但是我是否会重复将需要加载的每个视图中的硬币数量带入函数?我将向您展示当前执行的代码,它可以工作,但这不是最佳解决方案,因为我将在每个子组件中重复使用** get_coins **函数。
import React, { Component, useState, useEffect} from 'react'
import { userService } from '../_services';
import Template from '../Layouts/Template';
import { Button } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faExternalLinkSquareAlt } from '@fortawesome/free-solid-svg-icons'
function MyShopping() {
useEffect(() => {
get_coins();
}, []);
const [coins, setCoins] = useState([]);
function get_coins(){
userService.get_coins()
.then(resultCoins => {
setCoins(resultCoins);
});
}
function remove_coins(){
userService.remove_coins_data()
.then(result => {
if (result.status==200) {
get_coins();
}
})
}
return (
<Template dataCoins={coins}>
<div className="py-6">
<Button variant="success" onClick={remove_coins}>
Remove <FontAwesomeIcon icon={faExternalLinkSquareAlt} />
</Button>
</div>
</Template>
);
}
export { MyShopping };
import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav } from 'react-bootstrap';
const Template = ({ dataCoins, children }) =>(
<React.Fragment>
<Navbar collapseOnSelect expand="lg" className="cs_principal_nav">
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav>
<Nav.Link to="">
{dataCoins.expirables} Coins
</Nav.Link>
<Nav.Link to="">
{dataCoins.permanentes} Coins
</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
{children}
</React.Fragment>
);
export default Template;
谢谢