【问题标题】:How can I display my reversed array using the onClick event in React?如何使用 React 中的 onClick 事件显示我的反转数组?
【发布时间】:2019-09-29 21:58:07
【问题描述】:

我从 API 中提取数据并对其进行映射,但我想在用户单击 MARKET CAP 时反转顺序。我希望用户点击

<div>MARKET CAP</div>

在我想要替换我正在映射的这个数组的代码中: {props.coins.filter(searchingFor(search)).map... 和我做的相反的:

const [reverseCoin, setReverseCoin] = useState( 
 [...coin].filter(searchingFor(search)).reverse()
);

我不知道如何用反向数据替换原始数据,所以任何建议都会很棒。我正在使用 React、样式化的组件和钩子。这是我的代码:

import Button from "../../UI/Forms/Button/Button";
import styled from "styled-components";
import Icon from "../../assets/images/sort-solid.svg";
import SearchIcon from "../../assets/images/search-solid.svg";
import * as Styles from "../../components/Table/Tables.styles";
import { Link } from "react-router-dom";
import "./PriceList.scss"; 


function searchingFor(search) {
return function(x) {
 return x.name.toLowerCase().includes(search.toLowerCase()) || false;
};
} 

//MY FUCTIONAL COMPONENT*************

//one prop has been passed to this which I called it "coins"

const PriceList = props => {
console.log(props.coins);
const [coin, setCoin] = useState([]);
const [color, setColor] = useState("");
const [MarketCapLow, setMarketCapLow] = useState(false);
const [search, setSearch] = useState("");

/// this is the variable that holds the reversed array

const [reverseCoin, setReverseCoin] = useState( 
 [...coin].filter(searchingFor(search)).reverse()
);
const timeIntervels = ["1H", "24H", "1W", "1M", "1Y"];

useEffect(() => {
 setCoin(props.coins);
}, [props.coins]);

const updateSearch = e => {
 setSearch(e.target.value);
};



const handleClick = name => {
 setColor(name);
};

//creating a table for my data********

return (
 <TableContainer>
   <SearchBarMainContainer>
     <SearchBarContainer>
       <SearchInputContainer>
         <img
           src={SearchIcon}
           width="20"
           height="20"
           style={{ marginRight: "16px" }}
         />

         <SearchBarInput
           type="text"
           value={search}
           onChange={updateSearch}
           placeholder="Search coins..."
         />
       </SearchInputContainer>
       <SearchPriceChange>
         {timeIntervels.map(d => (
           <SearchPriceChangeItems
             id={d}
             onClick={() => {
               handleClick(d);
             }}
             className={color === d ? "purple" : "black"}
           >
             {d}
           </SearchPriceChangeItems>
         ))}
       </SearchPriceChange>
     </SearchBarContainer>
   </SearchBarMainContainer>

   <Styles.Tablestyles>
     <tbody>
       <Styles.TableRowStyles bg>
         <Styles.TabelHeadingStyles bg>#</Styles.TabelHeadingStyles>
         <Styles.TabelHeadingStyles bg>NAME</Styles.TabelHeadingStyles>
         <Styles.TabelHeadingStyles bg>PRICE</Styles.TabelHeadingStyles>
         <Styles.TabelHeadingStyles bg>CHANGE</Styles.TabelHeadingStyles>
         <Styles.TabelHeadingStyles bg>
           <Styles.MarketCap
             onClick={() => {
               setMarketCapLow(!MarketCapLow);

             }}
           >
             <div>MARKET CAP</div>
             <CoinIcon width height src={Icon} />
           </Styles.MarketCap>
         </Styles.TabelHeadingStyles>
         <Styles.TabelHeadingStyles bg>TRADE</Styles.TabelHeadingStyles>
       </Styles.TableRowStyles>

       {props.coins.filter(searchingFor(search)).map(coin => {
         const {
           rank,
           logo_url,
           name,
           ["1d"]: { price_change_pct },
           currency,
           price,
           market_cap
         } = coin;
         const newMarketPct = (price_change_pct * 100).toFixed(2);
         const newPrice = Math.floor(price * 100) / 100;
         const newMarketCap =
           Math.abs(market_cap) > 999999999
             ? Math.sign(market_cap) *
                 (Math.abs(market_cap) / 1000000000).toFixed(1) +
               "B"
             : Math.sign(market_cap) * Math.abs(market_cap);
         return (
           <Styles.TableRowStyles key={rank}>
             <Styles.TabelDataStyles>{rank}</Styles.TabelDataStyles>
             <Styles.TabelDataStyles grey flex>
               <CoinIcon style={{ marginRight: "12px" }} src={logo_url} />
               {name} ({currency})
             </Styles.TabelDataStyles>

             <Styles.TabelDataStyles>${newPrice}</Styles.TabelDataStyles>

             <Styles.TabelDataStyles
               style={
                 price_change_pct.charAt(0) === "-"
                   ? { color: "#ff2734" }
                   : { color: "#23cc9a" }
               }
             >
               {newMarketPct}%
             </Styles.TabelDataStyles>
             <Styles.TabelDataStyles>${newMarketCap}</Styles.TabelDataStyles>

             <Styles.TabelDataStyles>
               <Link to={`/prices/${coin.currency}`}>
                 <Button padding style={{ width: "60%" }}>
                   Trade
                 </Button>
               </Link>
             </Styles.TabelDataStyles>
           </Styles.TableRowStyles>
         );
       })}
     </tbody>
   </Styles.Tablestyles>
 </TableContainer>
);
}

【问题讨论】:

    标签: javascript arrays reactjs onclick dom-events


    【解决方案1】:

    我建议只使用存储在您的状态中的标志来切换数组的显示方式。当它们本质上是相同的数据时,这允许您避免将两个数组存储在您的状态中。您当然需要创建一个点击处理程序来更改 reversed 标志的值并将其放置在您希望点击发生的任何位置,但我看不出它在您的代码中的位置。

    [reversed, setReversed] = useState(false);
    
    ...
    // declare this variable somewhere inside your component outside the return statement. 
    // You have create a copy to prevent reverse() from mutating the prop in place.
    const displayedCoins = reversed ? Array.from(props.coins).reverse() : props.coins;
    
    ...
    
    {displayedCoins.filter(searchingFor(search)).map((coin) => { ... });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2020-12-31
      • 2020-08-09
      • 2020-10-02
      • 2021-09-13
      • 2020-02-22
      • 1970-01-01
      相关资源
      最近更新 更多