简体   繁体   English

ReactJS 如何更新数组中object中的state

[英]ReactJS How to update the state in object which is in the array

Hello I have one problem that I don't know ho to solve.您好,我有一个问题不知道要解决。

I have simple formular where the user type som inputs.我有简单的公式,用户可以在其中输入 som 输入。 After that when he clicks on the Button the firstName, lastname and picture will be display under the formular.之后,当他单击按钮时,名字、姓氏和图片将显示在公式下方。 And when I click on the input it will show the address and date.当我点击输入时,它会显示地址和日期。

But I have problem to do that.但我有问题要这样做。 In App.js I have a state which initialli si empty array and after click on submit button the user inputs is added to this empty array.在 App.js 中,我有一个 state,它最初是一个空数组,在单击提交按钮后,用户输入被添加到这个空数组中。 In Suggestions.js I map the sugestions array for displaying every suggestion from the user.在 Suggestions.js I map 中,sugestions 数组用于显示来自用户的每个建议。

In UserInputs.js I have a state where I add into state a 'visible' to false and I want to do, when I clicked on on suggestion in a list it will display the description and date below this particular sugestion.在 UserInputs.js 中,我有一个 state,我在 state 中添加了一个“可见”到 false 并且我想这样做,当我点击列表中的建议时,它会在这个特定的建议下方显示描述和日期。

I want to do it like this.我想这样做。 In App.js在 App.js 中

const detail = (suggestion) => {
        
        setSuggestions([...suggestions]); //but I don't know how to set state for particular 
                                            suggestion in the array.
      };

My code:我的代码:

App.js应用程序.js

import React, { useState } from "react";
import Suggestions from "./components/Suggestions";
import UserInputs from "./components/UserInputs";

function App() {
  const [suggestions, setSuggestions] = useState([]);

  const addNewSuggestion = (suggestion) => {
    setSuggestions([suggestion, ...suggestions]);
  };

  const detail = (suggestion) => {
    
    setSuggestions([...suggestions]);
  };

  console.log("suggestions", suggestions);

  return (
    <div className="app-container">
      <UserInputs addNewSuggestion={addNewSuggestion}></UserInputs>
      <Suggestions suggestions={suggestions} detail={detail}></Suggestions>
    </div>
  );
}

export default App;

Suggestions.js建议.js

import React from "react";

export default function Suggestions({ suggestions, detail }) {
  return (
    <div className="suggestion-container">
      <h1 className="suggestion-heading">Zoznam Podnetov</h1>
      {suggestions.map((suggestion, index) => {
        return (
          <div
            key={suggestion.id}
            className="suggestion"
            onClick={() => detail(suggestion)}
          >
            <div className="suggestion-number">{index + 1}</div>

            <div className="suggestion-details">
              <div className="suggestion-name">
                {suggestion.firstName}
                {` ${suggestion.lastName}`}
              </div>

              <div className="suggestion-address">{suggestion.address}</div>
              {suggestion.visible ? (
                <div className="suggestion-description">
                  <p>{suggestion.description}</p>
                  <p>Podnet bol pridaný: {suggestion.date}</p>
                </div>
              ) : null}
            </div>

            <div className="suggestion-picture">
              <img
                src={suggestion.picture}
                alt="obrázok"
                className="suggestion-picture"
              ></img>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Userinputs.js用户输入.js

import React, { useState } from "react";

export default function UserInputs({ addNewSuggestion }) {
  const randomId = Math.floor(Math.random() * 1000000);

  const [userInputs, setUserInputs] = useState({
    id: randomId,
    firstName: "",
    lastName: "",
    address: "",
    description: "",
    picture: null,
    date: new Date().toLocaleDateString(),
    visible: true,
  });

  const onInputChange = (event) => {
    setUserInputs({
      ...userInputs,
      [event.target.name]: event.target.value,
    });
  };

  const fileSelectHandler = (event) => {
    setUserInputs({
      ...userInputs,
      picture: URL.createObjectURL(event.target.files[0]),
    });
  };

  const onSubmit = (event) => {
    event.preventDefault();

    addNewSuggestion(userInputs);

    setUserInputs({
      id: randomId,
      firstName: "",
      lastName: "",
      address: "",
      description: "",
      picture: null,
      date: new Date().toLocaleDateString(),
      visible: true,
    });
  };

  return (
    <div>
      <form className="form-container">
        <div className="row">
          <label>Meno</label>
          <input
            autoFocus
            type="text"
            name="firstName"
            value={userInputs.firstName}
            onChange={onInputChange}
          ></input>
        </div>

        <div className="row">
          <label>Priezvisko</label>
          <input
            type="text"
            name="lastName"
            value={userInputs.lastName}
            onChange={onInputChange}
          ></input>
        </div>

        <div className="row">
          <label>Adresa</label>
          <input
            type="text"
            name="address"
            value={userInputs.address}
            onChange={onInputChange}
          ></input>
        </div>

        <div className="row">
          <label>Popis</label>
          <input
            type="text"
            name="description"
            value={userInputs.description}
            onChange={onInputChange}
          ></input>
        </div>

        <div className="row">
          <input type="file" onChange={fileSelectHandler}></input>
        </div>

        <button onClick={onSubmit} className="button">
          Odoslať
        </button>
      </form>
    </div>
  );
}

Thank you very much for your help.非常感谢您的帮助。

you can update the suggestion, where the id matches input suggestion and only update it.您可以更新建议,其中 ID 与输入建议匹配,并且只更新它。 Please find the code below:请找到下面的代码:

const detail = (suggestion) => { 

  let tempSuggestions = suggestions.map( (item) => {  
  if(item.id === suggestion.id) return suggestion
  return item
})
        
setSuggestions([...tempSuggestions]);                                            
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM