Javascript 推送onClick时未呈现过滤项(React)

Javascript 推送onClick时未呈现过滤项(React),javascript,reactjs,Javascript,Reactjs,我试图在满足特定条件时筛选选项列表。我想要的项目在I console.log时显示,但它不会呈现到页面。我已经创建了一个新的状态来保存过滤的项,这样我就不会改变[ListoOptions],但是当我这样做时,它不会呈现。有人能告诉我我做错了什么吗。我正在使用上下文API在状态之间进行遍历,而且我还没有做出反应,所以我可能会把事情搞砸。有人能给我指出正确的方向吗 const getTotal = () => { const newProfitArr = []

我试图在满足特定条件时筛选选项列表。我想要的项目在I console.log时显示,但它不会呈现到页面。我已经创建了一个新的状态来保存过滤的项,这样我就不会改变[ListoOptions],但是当我这样做时,它不会呈现。有人能告诉我我做错了什么吗。我正在使用上下文API在状态之间进行遍历,而且我还没有做出反应,所以我可能会把事情搞砸。有人能给我指出正确的方向吗

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>
const getTotal=()=>{
const newProfitArr=[]
for(设i=0;i{
if(isNaN(累加器)| isNaN(当前值)){
回流蓄能器;
}
否则返回累加器+当前值
}, 0);
}
useffect(()=>{
setTotalReturn(getTotal())
})
//这就是我使用新函数过滤选项数组列表的地方
const gainOptionsTab=()=>setNewTable(listooptions.filter(函数(选项)){
返回选项。总利润>0;
}).map(功能(选项){
返回选项
}))
//const lossOptionsTab=()=>setNewTable(listooptions.filter(函数(选项)){
//返回选项。总利润<0;
//}).map(函数(选项){
//返回选项
// }))
//更改活动类
函数addTabBackground(){
const tabs=document.querySelectorAll(“[data tab]”);
window.onload=函数(){
tabs.forEach(tab=>{
tab.addEventListener('单击',()=>{
tabs.forEach(tab=>{
tab.classList.remove('active')
})
tab.classList.add('active')
})
})
}
}
addTabBackground()
返回(
饲养员
=0?'green':'red'}>${totalReturn.toFixed(2)}
  • 全部
  • 增益
  • 损失
) } //试图过滤这个 常量handleSubmit=(e)=>{ e、 预防默认值() e、 target.reset(); 添加选项列表( { 时钟, 名称 价格, 许多选择, 总花费, 售出的期权数量, 选项PriceSoldat, 总利润 } ) } const getInputValue=(hookSetter)=>(e)=>{ 设{value}=e.target; 返回钩子设置器(值) } const addListoOptions=(列表)=>{ SetListoOptions([…ListoOptions,List]) } useffect(()=>{ 让getOptions=localStorage.getItem('options'); 如果(获取选项){ setListoOptions(JSON.parse(getOptions)) }否则返回空值 }, []); useffect(()=>{ localStorage.setItem('options',JSON.stringify(ListoOptions)) },[选项列表]) useffect(()=>{ SetTotalAmount花费((价格*金额选项)*100) 设定总利润((期权价格SOLDAT-价格)*(售出的期权数量*100)) }) //常量deleteItem=()=>{ //ListoOptions.filter // } 返回( 提交 日期 股票名称 期权价格 选择的数量 支出总额 期权出售价格 出售期权的金额 Proft {listOfOptions.map(选项=>{ 返回( {option.clock} {option.name.toUpperCase()} ${option.price} {option.amountOfOptions} ${option.TotalAmountSpeed.toFixed(2)} ${option.optionPriceSoldAt} {option.amountofoptionssell} =0?'green':'red'}>${option.totalProfit.toFixed(2)} ) })}
您能稍微澄清一下代码吗?例如,第一个
useffect
属于哪里?在您的代码中,它不是任何组件的一部分。对于
handleSubmit
等等也是如此。@Raphael我放在其中的useState函数。我认为代码不需要它们。您想让我把它们放进去吗?