【问题标题】:In React, how to setState a Data by using hook useState?在 React 中,如何使用 hook useState 来设置数据?
【发布时间】:2022-01-02 04:25:10
【问题描述】:

我刚刚开始学习 React 函数式组件和样式化组件。我试图 setState detailePageData

const const [marketPriceData, setMarketPriceData] = useState([]);

我尝试使用 JSON 文件设置 marketPriceData。

useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => setMarketPriceData(data.result.order_history));
  }, []);

当我 console.log marketPriceData.我懂了

在这里,我只需要每个数组中的价格。所以,当我 console.log(marketPriceData[0].price);我得到了我所期望的378000。 这是我的主要问题,我只需要每个数组的价格,例如; 378000、341000、388000等 我想我必须编辑这部分

useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => setMarketPriceData(data.result.order_history));
  }, []);

首先,我想“我可以使用 foreach 方法吗?或者 for 循环..?”我不确定如何设置存储 setMarketPriceData 的逻辑。你能帮我看看如何得到我期望的价格吗?

以防万一,我会留下整个代码,

import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { FaRegArrowAltCircleDown } from 'react-icons/fa';
import { Line } from 'react-chartjs-2';
import { Modal } from './components/Modal';
import TransitionHistoryModalStyling from '../ProductDetail/components/TransitionHistoryModalStyling';
import DropDownMenu from '../ProductDetail/components/DropDownMenu';
const options = {
  scales: {
    y: {
      beginAtZero: true,
    },
  },
};
export default function MarketPrice() {
  const [showModal, setShowModal] = useState(false);
  const [marketPriceData, setMarketPriceData] = useState([]);

  // https://github.com/reactchartjs/react-chartjs-2/blob/master/example/src/charts/Line.js
  const data = {
    labels: ['1', '2', '3', '4', '5', '6'],
    datasets: [
      {
        label: 'MarketPrice',
        data: marketPriceData,
        fill: false,
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgba(255, 99, 132, 0.2)',
      },
    ],
  };

  // useEffect(() => {
  //   let i = 1;
  //   if (i < detailPageData.order_history.length) {
  //     setMarketPriceData(detailPageData.order_history[i].price);
  //   }
  // },[]);

  const [detailPageData, setDetailPageData] = useState([]);

  useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => setDetailPageData(data.result));
  }, []);

  useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => setMarketPriceData(data.result.order_history));
  }, []);

  console.log(marketPriceData);
  console.log(marketPriceData[0].price);
  // console.log(detailPageData.market_price[0].sizes[0].size);
  // console.log(detailPageData.order_history);
  // console.log(detailPageData.order_history.length);
  // console.log(detailPageData.order_history[0].price);
  // console.log(detailPageData.order_history.price);
  const [currentMenuIndex, setCurrentMenuIndex] = useState(1);

  const handleSelectedMenu = tabIndex => {
    setCurrentMenuIndex(tabIndex);
  };

  const openModal = () => {
    setShowModal(prev => !prev);
  };
  return (
    <MarketPriceWrapper>
      <TitleWrapper>
        <MarketPriceTitle>시세</MarketPriceTitle>
        <ShowAllSizes>
          {/* <AllSize>230</AllSize>
          <FaRegArrowAltCircleDown /> */}
          <DropDownMenu className={DropDownMenu} />
        </ShowAllSizes>
      </TitleWrapper>
      <SalesGraphWrapper>
        <Line data={data} options={options} />
      </SalesGraphWrapper>
      <ButtonsWrapper>
        <Button
          isActive={currentMenuIndex === 1}
          onClick={() => handleSelectedMenu(1)}
        >
          체결 거래
        </Button>
        <Button
          isActive={currentMenuIndex === 2}
          onClick={() => handleSelectedMenu(2)}
        >
          판매 입찰
        </Button>
        <Button
          isActive={currentMenuIndex === 3}
          onClick={() => handleSelectedMenu(3)}
        >
          구매 입찰
        </Button>
      </ButtonsWrapper>
      <TableWrapper>
        <TableColumnSetting>
          <SizeName>사이즈</SizeName>
          <PriceName>거래가</PriceName>
          <DateName>거래일</DateName>
        </TableColumnSetting>
        <RowSection>
          {/* {detailPageData.market_price &&
            detailPageData.market_price.map(price => {
              return console.log(price.sizes[0]);
              <Size key={price.id}>
                <Size>{price.sizes[price.id].size}</Size>
                <Price>{price.sizes[price.id].avg_price}</Price>
                <Date>{price.date}</Date>
              </Size>
            })} */}
          <Size />
          <Price>24,000원</Price>
          <Date>99/11/17</Date>
        </RowSection>
        <RowSection>
          <Size />
          <Price>24,000원</Price>
          <Date>99/11/17</Date>
        </RowSection>
        <RowSection>
          <Size />
          <Price>24,000원</Price>
          <Date>99/11/17</Date>
        </RowSection>
        <RowSection>
          <Size />
          <Price>24,000원</Price>
          <Date>99/11/17</Date>
        </RowSection>
        <RowSection>
          <Size />
          <Price>24,000원</Price>
          <Date>99/11/17</Date>
        </RowSection>
        <OrderHistoryButton onClick={openModal}>
          체결 내역 더보기
        </OrderHistoryButton>
        <Modal showModal={showModal} setShowModal={setShowModal}>
          <TransitionHistoryModalStyling
            detailPageDataMarket={detailPageData}
          />
        </Modal>
      </TableWrapper>
    </MarketPriceWrapper>
  );
}

const MarketPriceWrapper = styled.div`
  width: 550px;
  margin-top: 40px;
  padding-left: 40px;
`;

const TitleWrapper = styled.div`
  display: flex;
  padding-top: 19px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebebeb;
`;
const SalesGraphWrapper = styled.div``;
const MarketPriceTitle = styled.span`
  padding-top: 4px;
  display: inline-block;
  line-height: 16px;
  font-weight: bold;
  color: #222;
`;
const ShowAllSizes = styled.div`
  margin-left: 370px;
`;
const AllSize = styled.span`
  display: inline-block;
  margin-right: 5px;
  margin-left: 350px;
  font-size: 18px;
`;

const ButtonsWrapper = styled.div`
  display: flex;
  justify-content: space-evenly;
  margin-top: 40px;
  border-radius: 10px;
  background-color: #f4f4f4;
`;

const Button = styled.button`
  display: block;
  margin: 2px;
  line-height: 16px;
  padding: 7px 0 9px;
  width: 400px;
  font-size: 13px;
  text-align: center;
  border-radius: 8px;
  border: none;
  background-color: ${props => (props.isActive ? '#ffff' : '#f4f4f4')};
  color: rgba(34, 34, 34, 0.8);
`;

const TableWrapper = styled.div`
  margin-top: 40px;
`;

const TableColumnSetting = styled.div`
  border-bottom: 1px solid #ebebeb;
  padding-bottom: 9px;
  text-align: right;
`;

const SizeName = styled.span`
  display: inline-block;
  margin-right: 250px;
  font-size: 12px;
  color: rgba(34, 34, 34, 0.5);
  font-weight: 400;
`;
const PriceName = styled.span`
  display: inline-block;
  margin-right: 150px;
  font-size: 12px;
  color: rgba(34, 34, 34, 0.5);
  font-weight: 400;
`;
const DateName = styled.span`
  display: inline-block;
  font-size: 12px;
  color: rgba(34, 34, 34, 0.5);
  font-weight: 400;
`;

const RowSection = styled.div`
  margin-top: 4px;
  text-align: right;
`;

const Size = styled.span`
  display: inline-block;
  margin-right: 240px;
  color: #222;
  font-size: 12px;
`;
const Price = styled.span`
  display: inline-block;
  margin-right: 130px;
  color: #222;
  font-size: 12px;
`;
const Date = styled.span`
  display: inline-block;
  color: #222;
  font-size: 12px;
`;

const OrderHistoryButton = styled.button`
  border: 1px solid #d3d3d3;
  margin-top: 40px;
  background-color: #ffffff;
  color: rgba(34, 34, 34, 0.8);
  font-weight: 400;
  padding: 0 18px;
  width: 500px;
  height: 42px;
  border-radius: 12px;
  font-size: 14px;
`;

【问题讨论】:

  • 你可以使用 .map(): .then(data =&gt; setMarketPriceData(data.result.order_history.map(i =&gt; i.price))); 检查这个map
  • @Bmsbharadwaj 首先,非常感谢您的帮助!它也完全有效。据我所知,“I”是指数组的索引,对吧?!
  • 不,i 不是索引。它是元素本身。所以,如果你的数组是arr = ['alice', 'bob', 'cory'],那么如果你是arr.map(i =&gt; i.length),那么i将对应于'alice'、'bob'等等......
  • @Bmsbharadwaj 谢谢你的详细解释。我明白你的意思了!

标签: reactjs styled-components react-functional-component


【解决方案1】:
const const [marketPriceData, setMarketPriceData] = useState([]);

useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => setMarketPriceData(data.result.order_history.map(item => item.price));
  }, []);

【讨论】:

  • 我认为您缺少.map
  • 是的,你是对的,谢谢
  • @vahidghadiri 首先,感谢您帮助我!它完全运作良好!如果您不介意,我可以问 item 是指数组的索引吗?你能用函数而不是箭头函数编写代码吗?有时,即使我经常使用箭头功能,我也无法理解它
  • @jiwanJeon94 map 方法是一个 HOF ,你必须将函数作为参数传递,item 只是一个名称,你可以使用任何你想要的......实际上你可以在你的 redux 中设置所有数据或在您的州,然后每当您想使用 price 时,在其上写一张地图......在这种情况下,您只将 price 设置为您的州,
  • @vahidghadiri 你在order_history.map之前输入了一个空格,请删除
【解决方案2】:

也许您可以在对象数据结果中使用地图。

data.result.order_history.map((item)=>{
   return item.price
}

这只会在您的数组中获得 de price 属性。

setMarketPriceData(data.result.order_history.map((item)=>{
   return item.price
})

【讨论】:

  • 首先感谢您的帮助!它完全运作良好!如果您不介意,我可以问 item 是指数组的索引吗?你能用函数而不是箭头函数编写代码吗?有时,即使我经常使用箭头功能,我也无法理解它
  • setMarketPriceData(data.result.order_history.map((item,index)=>{ return {price : item.price, index: index} }) 这样您就可以获得索引并获得新对象。关于函数我不知道它在地图中是如何工作的。我会检查
猜你喜欢
  • 2021-09-05
  • 2019-05-08
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多