代码之家  ›  专栏  ›  技术社区  ›  CCCC

反应-如何在UseEffect中使用useState更新对象数组中的特定字段

  •  1
  • CCCC  · 技术社区  · 5 年前

    首先,我创建一个对象数组 address useState .

    useEffect ,我想更新 地址 在我从API得到响应之后。

    [
        { id: "unit", label: "Unit", value: "Unit 1" },
        { id: "floor", label: "Floor", value: "Floor 1" },
        { id: "block", label: "Block", value: "Block 1" }
    ]
    

    我怎么做?

    import "./styles.css";
    import React, { useState, useEffect } from "react";
    
    export default function App() {
      const [address, setAddress] = useState([
        // the value will be updated in useEffect
        { id: "unit", label: "Unit", value: "" },  // Value should be Unit 1
        { id: "floor", label: "Floor", value: "" },// Value should be Floor 1
        { id: "block", label: "Block", value: "" } // Value should be Block 1
      ]);
    
      useEffect(() => {
        // let's pretent there is api GET request
        let responseData = {
          en: {
            unit: "Unit 1",
            floor: "Floor 1",
            Block: "Block 1"
          }
          // other language address which can be ignored
        };
    
        // How to update the update of address below??
    
      }, []);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    


    https://codesandbox.io/s/cranky-microservice-qjuhh?file=/src/App.js

    3 回复  |  直到 5 年前
        1
  •  3
  •   3limin4t0r    5 年前

    address 在中具有匹配的值 responseData 您可以使用:

    useEffect(() => {
      // let's pretent there is api GET request
      let responseData = {
        en: {
          unit: "Unit 1",
          floor: "Floor 1",
          Block: "Block 1"
        }
        // other language address which can be ignored
      };
      
      setAddress((address) => (
        address.map((item) => ({ ...item, value: responseData.en[item.id] }))
      ));
    }, []);
    

    上面的代码循环通过 地址 responseData.en

    我使用回调的原因是,如果新状态依赖于以前的状态,则应该使用回调。由于您只想更新项的单个属性(而不是完全替换状态),因此新状态取决于旧状态,因此使用回调。

        2
  •  0
  •   Joel Jaimon    5 年前

    您可以通过以下方式进行更新:

     useEffect(() => {
        // let's pretent there is api GET request
        let responseData = {
          en: {
            unit: "Unit 1",
            floor: "Floor 1",
            Block: "Block 1"
          }
          // other language address which can be ignored
        };
    
        // How to update the update of address below??
        setAddress((prevAddress) => [
          {
            ...prevAddress[0],
            value: responseData.en.unit
          },
          {
            ...prevAddress[0],
            value: responseData.en.floor
          },
          {
            ...prevAddress[0],
            value: responseData.en.Block
          }
        ]);
      }, []);
    

    供参考: https://codesandbox.io/s/hopeful-silence-gs1yq?file=/src/App.js:425-1015

        3
  •  0
  •   Andy    5 年前
    1. 将对象放入 responseData 这将它与语言区分开来。

    2. map 响应数据 .

    const data = [{ id: "unit", label: "Unit", value: "" },{ id: "floor", label: "Floor", value: "" },{ id: "block", label: "Block", value: "" }];
    const responseData = {en: {unit: "Unit 1",floor: "Floor 1",block: "Block 1"}};
    
    const obj = Object.values(responseData)[0];
    
    const result = data.map(({ id, value, ...rest }) => {
      return { id, value: obj[id], ...rest };
    });
    
    console.log(result);
        4
  •  0
  •   Nikhil bhatia    5 年前

    像这样尝试,如果en可用,它将需要en,否则无论第一个lang可用

          useEffect(() => {
            // let's pretent there is api GET request
            let responseData = {
              en: {
                unit: "Unit 1",
                floor: "Floor 1",
                Block: "Block 1"
              }
              // other language address which can be ignored
            };
            let languagePriority = null
    
            const availableLangs = Object.keys(responseData)
            if (responseData.en) {
             languagePriority = 'en'
            }
            if (!responseData.en && availableLangs.length) {
             languagePriority = availableLangs[0]
            }
            if (languagePriority) {
             const responseKeys = 
            Object.keys(responseData[languagePriority])
            const addressCopy = [...address]
            responseKeys.forEach(item => {
              addressCopy.find(addItem => {
              if (addItem.id === item) {
                addItem.value = response.en[item]
              }
              })
            })
            setAddress(addressCopy)
            }
            
            // How to update the update of address below??
    
          }, []);