#javascript #reactjs
#javascript #reactjs
Вопрос:
Я пытаюсь отфильтровать список параметров при выполнении определенных критериев. Нужный мне элемент отображается при консоли.журнал, но он не отображается на странице. Я создал новое состояние для хранения отфильтрованных элементов, чтобы я не изменял [listOfOptions] , однако, когда я это делаю, оно не отображается. Может кто-нибудь сказать мне, что я делаю не так. Я использую контекстный API для перехода между состояниями, и я новичок в React, поэтому я могу немного все испортить. Может кто-нибудь указать мне правильное направление?
const getTotal = () => {
const newProfitArr = []
for (let i = 0; i < listOfOptions.length; i ) {
newProfitArr.push(listOfOptions[i].totalProfit)
}
return newProfitArr.reduce((accumulator, currentValue) => {
if (isNaN(accumulator) || isNaN(currentValue)) {
return accumulator;
}
else return accumulator currentValue
}, 0);
}
useEffect(() => {
setTotalReturn(getTotal())
})
//This is where I am filtering the list of options array with the new function
const gainOptionsTab = () => setNewTable(listOfOptions.filter(function (option) {
return option.totalProfit > 0;
}).map(function (option) {
return option
}))
// const lossOptionsTab = () => setNewTable(listOfOptions.filter(function (option) {
// return option.totalProfit < 0;
// }).map(function (option) {
// return option
// }))
//change active class
function addTabBackground() {
const tabs = document.querySelectorAll('[data-tab]');
window.onload = function () {
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(tab => {
tab.classList.remove('active')
})
tab.classList.add('active')
})
})
}
}
addTabBackground()
return (
<nav className="navbar">
<h1 id="gains">stock<span>ER</span></h1>
<h2 style={{ color: totalReturn >= 0 ? 'green' : 'red' }}>${totalReturn.toFixed(2)}</h2>
<ul>
<li data-tab="all" className="active">All</li>
<li onClick={gainOptionsTab} data-tab="gains">Gains</li>
<li data-tab="losses" id="lost" className="losses">Losses</li>
</ul>
</nav >
)
}
//Trying to filter this
const handleSubmit = (e) => {
e.preventDefault()
e.target.reset();
addListOfOptions(
{
clock,
name,
price,
amountOfOptions,
totalAmountSpent,
amountOfOptionsSold,
optionPriceSoldAt,
totalProfit
}
)
}
const getInputValue = (hookSetter) => (e) => {
let { value } = e.target;
return hookSetter(value)
}
const addListOfOptions = (lists) => {
setListOfOptions([...listOfOptions, lists])
}
useEffect(() => {
let getOptions = localStorage.getItem('options');
if (getOptions) {
setListOfOptions(JSON.parse(getOptions))
} else return null
}, []);
useEffect(() => {
localStorage.setItem('options', JSON.stringify(listOfOptions))
}, [listOfOptions])
useEffect(() => {
setTotalAmountSpent((price * amountOfOptions) * 100)
setTotalProfit((optionPriceSoldAt - price) * (amountOfOptionsSold * 100))
})
// const deleteItem = () => {
// listOfOptions.filter
// }
return (
<div className="formoutputs">
<form onSubmit={handleSubmit}>
<input type="text" className="input stockname" placeholder="Enter Stock Symbol" onChange={getInputValue(setName)} />
<input type="text" className="input stockprice" placeholder="Enter Option Price" onChange={getInputValue(setPrice)} />
<input type="text" className="input stockamount" placeholder="Enter Number Of Option" onChange={getInputValue(setAmountOfOptions)} />
<input type="text" className="input stockpricesold" placeholder="Enter Option Price Sold" onChange={getInputValue(setOptionPriceSoldAt)} />
<input type="text" className="input stockamountsold" placeholder="Enter Number Of Option Sold" onChange={getInputValue(setAmountOfOptionsSold)} />
<button type="submit" className="btn">Submit</button>
</form>
<div className="outputs" >
<table>
<thead>
<tr>
<th>Date</th>
<th>Stock Name</th>
<th>Price Of Option</th>
<th>Number Of Options</th>
<th>Total Amount Spent</th>
<th>Option Sold At</th>
<th>Amount Of Options Sold</th>
<th>Proft</th>
</tr>
</thead>
{listOfOptions.map(option => {
return (
<tbody>
<tr>
<td>{option.clock}</td>
<td>{option.name.toUpperCase()}</td>
<td>${option.price}</td>
<td>{option.amountOfOptions}</td>
<td>${option.totalAmountSpent.toFixed(2)}</td>
<td>${option.optionPriceSoldAt}</td>
<td>{option.amountOfOptionsSold}</td>
<td style={{ color: option.totalProfit >= 0 ? 'green' : 'red' }}>${option.totalProfit.toFixed(2)}</td>
</tr>
</tbody>
)
})}
</table>
</div>
</div>
Комментарии:
1. Не могли бы вы немного прояснить код? Например, где первое
useEffect
принадлежит? В вашем коде это не является частью какого-либо компонента. То же самое дляhandleSubmit
и так далее.2. @Raphael Те, в которых используются функции useState, которые я ввел. Я не думал, что они нужны для кода. Вы хотите, чтобы я вставил их?