【发布时间】:2021-12-27 20:37:19
【问题描述】:
我正在创建一个股票应用程序,它允许用户通过调用 Stock API 来搜索股票价格并搜索任何股票并取回其价格。
我将价格存储在表格中,但是我也希望能够将用户输入的内容存储到表格中。
我的策略是将用户的搜索输入存储到数组“symbolArray”中,将 api 信息存储到“dataArray”中。”
所以这是我的问题。我能够映射“dataArray”并将其呈现到表格中。但是我需要映射“symbolArray”并将其渲染到已经从“数据数组”渲染项目的表中。
这就是我目前所拥有的
const Quotes = ()=> {
//I call their states
const [symbolArray, setSymbolArray] = useState([])
const [dataArray, setDataArray] = useState([])
//this function stores, and calls the api data that the user searches for
function getData() {
fetch(url)
.then(res => res.json())
.then(data =>{
dataArray.push(data)
})
}
// this is also activated when the user searchs. their input is pushed to the array of stock ticker symbols
const addingStuff = ()=> {
symbolArray.push(input)
}
return (
<>
{/* here a user searches for stock */}
<div class="input-group">
<input id="searchBar" type="search" class="form-control rounded search-bar" placeholder="Enter Ticker Symbol" aria-label="Search"
aria-describedby="search-addon" value={input} onInput={e => setInput(e.target.value)} />
<button type="button" class="searchButton btn p-2 bg-succ" id="searchButton" onClick={()=> {getData(); addingStuff(); }}>Quote This Stock</button>
</div>
{/* here is my table */}
<table class='table'>
<thead>
<tr>
{/* table headers*/}
<th scope='col'>Symbol</th>
<th scope='col'>Current Price</th>
<th scope='col'>Day High</th>
<th scope='col'>Day Low</th>
<th scope='col'>Price Change</th>
<th scope='col'>Open Price</th>
<th scope='col'>Percentage Change</th>
<th scope='col'>Previous Close</th>
</tr>
</thead>
<tbody>
{/* i call the function that gets and stores the data */}
{getData ?
dataArray.map((stock, index) => {
const {c, d, dp, h, l, o, pc} = stock;
return (
<tr key={index}>
{/* here is the issue where the 2 arrays clash */}
<th scope='row'>{symbolArray.map((symbol, i) => { return i})}</th>
<td>{c}</td>
<td>{d}</td>
<td>{dp}</td>
<td>{h}</td>
<td>{l}</td>
<td>{o}</td>
<td>{pc}</td>
</tr>
)
})
: null }
</>
}
【问题讨论】:
-
你忘记了
addingStuff中的input参数,它应该是const addingStuff = input => ... -
您好 Ameer,非常感谢您的评论!不幸的是,当我继续搜索股票时,将数据从我的数组中推出并让字段变为空白。不过还是谢谢!仍然会投票回复
标签: javascript reactjs jsx