如何使用useState React进行映射

时间:2019-11-05 17:46:43

标签: javascript reactjs frontend

我有一个输入字段,我想在其中输入数字;然后,该数字应存储在该状态下的指定键“ mktratedelta”中。

我正在通过映射做到这一点。由于某些原因,我无法在输入字段中键入。这是正确的方法,以及如何解决此问题?

const [marketEstimateDataBCAssets, setmarketEstimateData] = useState([
    {
      name: "Lombard",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.03,
      mktrateestimate: 0.04
    },
    {
      name: "Other Secured",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.033,
      mktrateestimate: 0.04
    },
    {
      name: "Unsecured",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.0333,
      mktrateestimate: 0.04
    }
  ]);

{Object.keys(marketEstimateDataBCAssets).map(function(key) {
        return (
          <Segment>
            <div> {marketEstimateDataBCAssets[key].name}</div>
            <div> {marketEstimateDataBCAssets[key].prevgroupinputrate}</div>
            <div> {marketEstimateDataBCAssets[key].currgroupinputrate}</div>
            <input
              value={marketEstimateDataBCAssets[key].mktratedelta}
              onChange={e =>
                (marketEstimateDataBCAssets[key].mktratedelta = e.target.value)
              }
            />
            <div> {marketEstimateDataBCAssets[key].mktrateestimate}</div>
          </Segment>
        );


4 个答案:

答案 0 :(得分:1)

这里是如何将逻辑分为两个部分并呈现资产列表的示例

function myAwesomeComponent() {
  const [marketData, setMarketData] = useState([
    {
      id: 0,
      name: 'Lombard',
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.03,
      mktrateestimate: 0.04,
    },
    {
      id: 1,
      name: 'Other Secured',
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.033,
      mktrateestimate: 0.04,
    },
    {
      id: 2,
      name: 'Unsecured',
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.0333,
      mktrateestimate: 0.04,
    },
  ]);

  const onChange = (asset) => (event) => {
    setMarketData((oldMarketData) => {
      const index = oldMarketData.indexOf(asset);
      const oldAsset = oldMarketData[index];
      const newMarketData = [...oldMarketData];
      newMarketData[index] = {
        ...oldAsset,
        mktratedelta: event.target.value,
      };
      return newMarketData;
    });
  };

  return (
    <>
      {marketData.map((asset) => (
        <Asset asset={asset} onChange={onChange} />
      ))}
    </>
  );
}

const Asset = ({ asset, onChange }) => (
  <Segment key={asset.id}>
    <div> {asset.name}</div>
    <div> {asset.prevgroupinputrate}</div>
    <div> {asset.currgroupinputrate}</div>
    <input value={asset.mktratedelta} onChange={onChange(asset)} />
    <div> {asset.mktrateestimate}</div>
  </Segment>
);

如果您对marketData数组中的属性名称有影响,则应考虑使用camelCase,因此

{
  id: 0,
  name: 'Lombard',
  prevgroupinputrate: 0.01,
  currgroupinputrate: 0.02,
  mktratedelta: 0.03,
  mktrateestimate: 0.04,
}

成为

{
  id: 0,
  name: 'Lombard',
  prevGroupInputrate: 0.01,
  currGroupInputrate: 0.02,
  mktRateDelta: 0.03,
  mktRateEstimate: 0.04,
}

答案 1 :(得分:0)

您正在直接更改state。不要这样尝试这样的事情:

 return (
           <>
      {marketEstimateDataBCAssets.map((item, key) => (
        <div>
          <div> {item.name}</div>
          <div> {item.prevgroupinputrate}</div>
          <div> {item.currgroupinputrate}</div>
          <input
            value={item.mktratedelta}
            onChange={e => {
              const newArr = marketEstimateDataBCAssets.map(el => {
                if (el.name === item.name) {
                  return { ...el, mktratedelta: parseFloat(e.target.value) };
                }
                return el;
              });
              console.log(newArr);

              return setmarketEstimateData([...newArr]);
            }}
          />
          <div> {item.mktrateestimate}</div>}
        </div>
      ))}
    </>

        );

这里有一个快速的demo。感谢@Titus指出了这个问题。

答案 2 :(得分:0)

代码存在一些问题。 1.您无法对数组执行Object.keysmarketEstimateDataBCAssets是代码中的数组);

  1. 您不能直接将值分配给状态对象。

您只需删除Object.keys即可解决第一个问题;

对于第二个问题,

只需创建一个函数即可将数组键值与输入值一起传递。在函数中,使用创建数组并更新索引对象的值,然后只需将新数组数据传递到setmarketEstimateData

因此代码将是:

const [marketEstimateDataBCAssets, setmarketEstimateData] = useState([
  {
    name: "Lombard",
    prevgroupinputrate: 0.01,
    currgroupinputrate: 0.02,
    mktratedelta: 0.03,
    mktrateestimate: 0.04
  },
  {
    name: "Other Secured",
    prevgroupinputrate: 0.01,
    currgroupinputrate: 0.02,
    mktratedelta: 0.033,
    mktrateestimate: 0.04
  },
  {
    name: "Unsecured",
    prevgroupinputrate: 0.01,
    currgroupinputrate: 0.02,
    mktratedelta: 0.0333,
    mktrateestimate: 0.04
  }
]);

function updateValue(e, key) {
  let data =  setmarketEstimateData;
  data[key].mktratedelta = e.target.value;
  marketEstimateDataBCAssets.map(data);
}

{marketEstimateDataBCAssets.map(function(item,key) {
  return (
    <Segment>
      <div> {item.name}</div>
      <div> {item.prevgroupinputrate}</div>
      <div> {item.currgroupinputrate}</div>
      <input
        value={item.mktratedelta}
        onChange={e => updateValue(e, updateValue(e, key))}
      />
      <div> {item.mktrateestimate}</div>
    </Segment>
  );
}


答案 3 :(得分:0)

这样的事情。


import React from 'react';

const Component = () => {

  const [marketEstimateDataBCAssets, setmarketEstimateData] = useState([
    {
      name: "Lombard",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.03,
      mktrateestimate: 0.04
    },
    {
      name: "Other Secured",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.033,
      mktrateestimate: 0.04
    },
    {
      name: "Unsecured",
      prevgroupinputrate: 0.01,
      currgroupinputrate: 0.02,
      mktratedelta: 0.0333,
      mktrateestimate: 0.04
    }
  ]);

  const preSetEstimateData = (value, itemId) => {

    const item = marketEstimateDataBCAssets[itemId];
    const newItem = {
      ...item,
      mktrateestimate: value,
    }

    setmarketEstimateData([
      ...marketEstimateDataBCAssets.slice(0, itemId),
      newItem,
      ...marketEstimateDataBCAssets.slice(itemId)
    ]);
  };

  return (
    <div>
      {
        marketEstimateDataBCAssets.map((item, id) => {
          return (
            <Segment>
              <div> {item.name}</div>
              <div> {item.prevgroupinputrate}</div>
              <div> {item.currgroupinputrate}</div>
              <input
                value={item.mktratedelta}
                onChange={e => preSetEstimateData(e.target.value, id)}
              />
              <div> {item.mktrateestimate}</div>
            </Segment>
          )
        })
      }
    </div>
  )
}

export default Component;