Currently, in Portfolio component, counter prop is not getting displayed, but stock prop is getting displayed fine. Portfolio component is getting mapped by stockInfo to receive props, but I added another separate prop called counter, but it's not working out. What would be the correct way to pass down counter prop to Portfolio component, when Portfolio component is being iterated by another prop?
function App() {
const [stockInfo, setStockInfo] = useState([{ quote: "SPY", cost:320, currentHolding: true }]);
const [counter, setCounter] = useState(1);
let showChart = true;
const addStockSymbol = (quote, cost) => {
const newStockInfo = [...stockInfo, { quote: quote, cost: Number(cost), currentHolding: true }];
setStockInfo(newStockInfo);
setCounter(prevCounter => prevCounter + 1);
};
return (
<div>
<PortfolioForm addStockSymbol={addStockSymbol} />
{stockInfo.map((stock, index) => (
<div>
<Portfolio
key = {index}
index = {index}
stock={stock}
counter={counter}
/>
</div>
))}
</div>
)
}
export default App;
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './Portfolio.css';
const Portfolio = ({stock}, {counter}) => {
const [stockData, setStockData] = useState([]);
useEffect(() => {
(async () => {
const data = await axios(
`https://finnhub.io/api/v1/quote?symbol=${stock.quote}&token=${process.env.REACT_APP_API_KEY}`
);
setStockData(data.data);
})();
},[]);
console.log(counter);
return (
<ul className="table-headings">
<li>{counter}</li>
<li>{stock.quote}</li>
<li>${stockData.pc}</li>
<li>${stock.cost}</li>
<li>320 days</li>
<li>36.78%</li>
</ul>
)
}
export default Portfolio;
Function components get props
as argument, then you can destruct the props object to get only specific properties.
What you're doing right now in the Portfolio
component is destructing stock
from the props
object (which is fine), but for counter
you're destructing the second argument (which is also an object that represents forwardRef , but in this case there is not ref so its an empty object)
So, to fix the problem, just replace the Portfolio
parameters from ({stock}, {counter})
to ({stock, counter})
which destructs these two properties from props
You can learn more about destructuring assignment in here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.