【发布时间】:2021-07-09 12:33:46
【问题描述】:
我是 React JS 的新手,我正在尝试构建一个小项目来学习。 到目前为止,我做得很好,但我相信我的应用程序渲染过多,这使我无法获得我有兴趣添加的另一个功能 - 一个本地存储保存最后一次搜索的股票。
我的项目是一个简单的股票搜索应用程序,通过股票名称或股票代码获取股票价格。
我做错了什么? 我得到了我想要的价格,但是它需要太多的效果图。如果我只做一个,我得到的价格只是一个普通的 0,而不是实际价格。 当我按照下面发布的代码进行操作时,它显示了正确的价格,但我相信我错过了一些东西。
我对 React 比较陌生,所以我猜这是学习的一部分 :)
我的另一个问题,据我了解,react-router 是假设保存最后输入的值。我确实使用了react router,这个页面上的渲染是否再次更改为默认值?
PS,当我尝试将 currentStock 的默认状态保持为空时,我得到了一些奇怪的值,我认为这是 API 本身的问题。
这是我的代码:
const Stocks = () => {
const [currentStock, setCurrentStock] = useState('AAPL');
const [currentPrice, setCurrentPrice] = useState('Loading...');
const [stockFromClick, setClick] = useState();
useEffect( () => {
if(currentPrice === 0){
setCurrentPrice('Ready!')
}
const fetchData = async() =>{
const getSymbol = await axios(`https://finnhub.io/api/v1/search?q=${currentStock}&token=${API_KEY}`);
setCurrentStock(getSymbol.data.result[0].symbol);
const getPrice = await axios (`https://finnhub.io/api/v1/quote?symbol=${currentStock}&token=${API_KEY}`)
setCurrentPrice(getPrice.data.c)
}
fetchData();
console.log(currentPrice);
} , [stockFromClick, currentPrice]);
const handleClick = () =>{
setCurrentPrice('Loading... Please allow the system a few seconds to gather all the information');
setClick(currentStock);
console.log(currentStock);
}
return (
<div>
Stocks!<br></br>
<input type="text" placeholder="Search a Company" value={currentStock} onChange={e => setCurrentStock(e.target.value)} /><br></br>
<button type="button" onClick={handleClick}> Search</button><br></br>
{currentPrice}
</div>
)
}
export default Stocks;
【问题讨论】:
-
您的
useEffect每次currentPrice更改时都会运行,但它也会更改currentPrice的值
标签: javascript reactjs performance react-router react-hooks