Save data in a special order when click on button

前端 未结 1 680
轮回少年
轮回少年 2020-11-30 15:55

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.

相关标签:
1条回答
  • 2020-11-30 16:19

    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

    0 讨论(0)
提交回复
热议问题