单击按钮时以特殊顺序保存数据 [英] Save data in a special order when click on button

查看:50
本文介绍了单击按钮时以特殊顺序保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个应用程序,用户可以在其中向我的示例中的特定 car 添加一些注释.用户必须能够添加评论并对汽车进行评分.

const App = () =>{const [state, setState] = useState({可见: false });const [myData, setMyData] = useState([]);const showModal = () =>{设置状态({可见:真实});};const handleOk = (e) =>{设置状态({可见:假});console.log("所有数据", myData);};const handleCancel = (e) =>{控制台日志(e);设置状态({可见:假});};返回 (<><Button type="primary" onClick={showModal}>打开模态</按钮><模态标题="基本模态"可见={state.visible}onOk={handleOk}onCancel={handleCancel}><Data setMyData={setMyData}/></模态></>);};

console.log("all data", myData); 中,我必须得到结果.
现在我有这一系列的项目:

const data = [{汽车: [{车名:宝马",车速:100}],carCat: "4X4 车",汽车颜色:蓝色"},{汽车: [{车名:奥迪",车速:150}],carCat: "快车",汽车颜色:红色"},{汽车: [{汽车名称:梅赛德斯",车速:170}],carCat: "舒适车",汽车颜色:白色"}];

当用户打开模态时,他将看到 3 个数据块,在那里他将能够添加评论和评分.
场景:如果用户在 4X4 car 块(评分和评论)中添加数据,则以这种方式.然后保存数据,点击save按钮,数组应该以下一种方式改变:

const data = [{汽车: [{车名:宝马",车速:100}],carCat: "4X4 车",汽车颜色:蓝色",rate: 3,//取决于用户速率评论:[用户的文本"]//取决于用户},{汽车: [{车名:奥迪",车速:150}],carCat: "快车",汽车颜色:红色"},{汽车: [{汽车名称:梅赛德斯",车速:170}],carCat: "舒适车",汽车颜色:白色"}];

如果用户不仅为一个块添加数据,而是为所有块添加数据,则数组中的所有数据都应根据以前的方式更改,具体取决于用户输入.
现在我保存时只得到一组数据.
问题:如何实现我上面描述的内容?感谢您的帮助.
演示:https://codesandbox.io/s/hungry-margulis-4yx9b?file=/Data.js:60-489

解决方案

为了让你的场景工作,你应该更新 组件如下:

const Data = () =>{const [汽车,setCars] = useState(data);const setRate = (category, rate) =>{const newCars = [...汽车];让 index = newCars.findIndex((c) => c.carCat === category);newCars[index] = Object.assign(newCars[index], { rate });setCars(newCars);};const setComment = (category, comment) =>{const newCars = [...汽车];让 index = newCars.findIndex((c) => c.carCat === category);newCars[index] = Object.assign(newCars[index], { comment });setCars(newCars);};返回 (<div>{cars.map((i) => {返回 (<div key={i.carCat}><span>{i.carCat}</span><设置数据setRate={(rate) =>setRate(i.carCat, rate)}setComment={(comment) =>setComment(i.carCat, 评论)}/>

);})}

);};

const SetData = ({ setRate, setComment }) =>{返回 (<div><Rate onChange={setRate}/><输入onChange={(e) =>setComment(e.target.value)}占位符=评论"/>

);};

这里最重要的部分是如何传递组件的setRatesetComment props.

setRate(i.carCat, rate)}setComment={(comment) =>setComment(i.carCat, 评论)}/>


更新 1

<块引用>

如何创建评论数组,例如用户添加一次评论并单击确定按钮保存,然后再次打开模态并为该块添加另一个评论,并以这种方式创建一个评论数组.

基本上,您需要提升状态 组件.使用此示例作为指导:https://codesandbox.io

I create an application where user can add some notes to a specific car in my examlpe. User has to be able to add a comment and to rate the car.

const App = () => {
  const [state, setState] = useState({ visible: false });
  const [myData, setMyData] = useState([]);

  const showModal = () => {
    setState({
      visible: true
    });
  };

  const handleOk = (e) => {
    setState({
      visible: false
    });
    console.log("all data", myData);
  };

  const handleCancel = (e) => {
    console.log(e);
    setState({
      visible: false
    });
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        Open Modal
      </Button>
      <Modal
        title="Basic Modal"
        visible={state.visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Data setMyData={setMyData} />
      </Modal>
    </>
  );
};

In console.log("all data", myData); i have to get the result.
Now i have this array of items:

const data = [
  {
    cars: [
      {
        carName: "bmw",
        carSpeed: 100
      }
    ],
    carCat: "4X4 car",
    carColor: "blue"
  },
  {
    cars: [
      {
        carName: "audi",
        carSpeed: 150
      }
    ],
    carCat: "fast car",
    carColor: "red"
  },
  {
    cars: [
      {
        carName: "mercedes",
        carSpeed: 170
      }
    ],
    carCat: "confort car",
    carColor: "white"
  }
];

When user will open the modal, he will se 3 blocks of data, there he will be able to add comments and a rate.
Scenario: In this way if user adds data in the 4X4 car block (rate and comment). and after that saves the data, clicking on save button, the array should change in the next way:

const data = [
  {
    cars: [
      {
        carName: "bmw",
        carSpeed: 100
      }
    ],
    carCat: "4X4 car",
    carColor: "blue",
    rate: 3,  // depends by the user rate
    comments: ["user's text"] // depends by user
  },
  {
    cars: [
      {
        carName: "audi",
        carSpeed: 150
      }
    ],
    carCat: "fast car",
    carColor: "red"
  },
  {
    cars: [
      {
        carName: "mercedes",
        carSpeed: 170
      }
    ],
    carCat: "confort car",
    carColor: "white"
  }
];

If user add data not just for one block but for all, all data from array should change according to the previous way, depending by the user input.
Now i get just an array of data when i save.
Question: How to implemement what i described above? Thanks for help.
demo: https://codesandbox.io/s/hungry-margulis-4yx9b?file=/Data.js:60-489

解决方案

To make your scenario working you should update <Data /> and <SetData /> components as follows:

const Data = () => {
  const [cars, setCars] = useState(data);

  const setRate = (category, rate) => {
    const newCars = [...cars];
    let index = newCars.findIndex((c) => c.carCat === category);
    newCars[index] = Object.assign(newCars[index], { rate });

    setCars(newCars);
  };

  const setComment = (category, comment) => {
    const newCars = [...cars];
    let index = newCars.findIndex((c) => c.carCat === category);
    newCars[index] = Object.assign(newCars[index], { comment });

    setCars(newCars);
  };

  return (
    <div>
      {cars.map((i) => {
        return (
          <div key={i.carCat}>
            <span>{i.carCat}</span>
            <SetData
              setRate={(rate) => setRate(i.carCat, rate)}
              setComment={(comment) => setComment(i.carCat, comment)}
            />
          </div>
        );
      })}
    </div>
  );
};

const SetData = ({ setRate, setComment }) => {
  return (
    <div>
      <Rate onChange={setRate} />
      <input
        onChange={(e) => setComment(e.target.value)}
        placeholder="comment"
      />
    </div>
  );
};

The most important part here is how setRate and setComment props of <SetData /> component are passed.

<SetData
  setRate={(rate) => setRate(i.carCat, rate)}
  setComment={(comment) => setComment(i.carCat, comment)}
/>


Update 1

How to create an array of comments, for example user add one time a comment and clicks on OK button to save, and after that again open the modal and also add another comment for that block, and in this way to create an array of comments.

Basically, you need to lift state up even further to <App /> component. Use this example as guidance: https://codesandbox.io

这篇关于单击按钮时以特殊顺序保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆