【问题标题】:How to update/add new data to react functional component object?如何更新/添加新数据以响应功能组件对象?
【发布时间】:2021-12-27 13:34:21
【问题描述】:

我正在尝试创建一个函数来更新反应功能组件中的对象。 我想做的是:

const [content, setContent] = useState({});
const applyContent = (num: number, key: string, val: string) => {
  if (content[num] === undefined) {
    content[num] = {};
  }
  content[num][key] = val;
  setNewContent(newInput);
};

但我不断收到一条错误消息,指出内容没有 num 属性, 在 vanilla JS 中它可以工作,我缺少什么让它与反应功能组件一起工作?

【问题讨论】:

  • 您没有指定预期的 type 内容,因此它被推断为没有属性的对象。使用 `useState. 的generic 类型参数。

标签: javascript reactjs react-functional-component


【解决方案1】:

content 是一个只读值。你不能直接改变它。仅用于显示数据或将此数据复制到另一个帮助器值。

setContent 是一个设置内容的函数。

设置数据有两种方式

setContent(value) <-- set directly 
setContent(prevState => {
    return {
        ...prevState,
        ...value
    }
})

在第二个示例中,您将使用以前的值,复制它,然后用新值覆盖它。如果您只更新对象或数组的一部分,这很有用。

如果您使用的是深度嵌套的对象,浅拷贝可能还不够,您可能需要先对内容值进行深度拷贝。如果不是,则使用 prevState 示例仅更新该内容的一部分

const [content, setContent] = useState({});

const applyContent = (num:number,key:string,val:string) => {
const newContent = {...content} // Shallow copy content
    if (content[num] === undefined) {
      //content[num] = {}; <-- you cant directly change content. content is a readOnly value
    newContent[num] = {}
    
    }
    newContent[num][key] = val;
    //setNewContent(newInput);
      setContent(newContent) // <-- use "setContent" to change "content" value
  }

【讨论】:

    【解决方案2】:

    组件状态的设置器拼写错误。看看下面的代码。

    import React, { useState } from 'react';
    import './style.css';
    
    export default function App() {
      const [content, setContent] = useState({});
    
      const applyContent = (num, key, val) => {
        //gets the appropriate inputs
        let updatedContent = content;
        let value = {};
        value[key] = val;
    
        updatedContent[num] = value; //this inserts a new object if not present ot updates the existing one.
    
        setContent({ ...updatedContent });
      };
    
      return (
        <div>
          <h1>Click buttons to change content</h1>
          <p>{JSON.stringify(content)}</p>
          <button onClick={(e) => applyContent(0, 'a', 'b')}>Add</button>
          <button onClick={(e) => applyContent(1, 'c', 'd')}>Add</button>
          <button onClick={(e) => applyContent(0, 'e', 'f')}>Add</button>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-09-15
      • 2021-01-04
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多