简体   繁体   English

如何在不覆盖先前状态的情况下将状态更新为对象数组

[英]How can I update state as an array of objects without overriding previous state

I want to update setTopic without overriding previous state.我想更新 setTopic 而不覆盖以前的状态。 But I am getting topic is not iterable error.但我得到的topic is not iterable错误。

What I tried?我尝试了什么? I tried looking a different examples on stack overflow, But still couldn't figure out how to append updated state without losing previous state.我尝试查看有关堆栈溢出的不同示例,但仍然无法弄清楚如何在不丢失先前状态的情况下附加更新状态。

Also, which is a better way to save multiple topics : an array of objects, simply objects or simply array?另外,哪个是保存多个主题的更好方法:对象数组、简单对象或简单数组?

const AddTopic = (props) => {
  const { subjectName } = props;
  const [topic, setTopic] = useState([
    {
      topics: [
        {
          id: Math.random().toString(36).substr(2, 7),
          topicName: "topic name",
          subject: subjectName,
        },
      ],
    },
  ]);

  const addTopicHandler = () => {

    setTopic(
      [...topic].map((item) => {
        return {
          ...item,
          id: Math.random().toString(36).substr(2, 7),
          topicName: "another topic name",
          subject: subjectName,
        };
      })
    );
  };
  console.log(topic);
  1. Instead of the child component using state lift the state to a parent component, and then just create dumb components from the state.而不是使用状态的子组件将状态提升到父组件,然后从状态创建哑组件。

  2. Rename your state.重命名您的州。 Call it topics , and the update function setTopics .称其为topics ,更新函数为setTopics Initialise it as an array, not an array containing one object containing an array.将其初始化为一个数组,而不是一个包含一个包含数组的对象的数组。

  3. You can't immediately log an updated state.您无法立即记录更新的状态。 You need to use useEffect to watch for changes in state, and then log something.您需要使用useEffect来观察状态的变化,然后记录一些东西。

 const { useEffect, useState } = React; // Topic component - just gets handed the // subject (in this example) in the props function Topic({ subject }) { return <div>{subject}</div>; } function Example() { // Initialise `topics` as an array const [ topics, setTopics ] = useState([]); // When `topics` is updated, log the updated state useEffect(() => console.log(topics), [topics]); // Helper function that maps over the state and // produces an array of topics function getTopics() { return topics.map(topic => <Topic subject={topic.subject} />); } // Helper function to add a new topic object // to the topics state function addTopic() { const obj = { subject: 'Math', topic: 'Fish' }; setTopics([...topics, obj ]); } return ( <div> <div>{getTopics()}</div> <button onClick={addTopic}>Add topic</button> </div> ); }; ReactDOM.render( <Example />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

Try to replace [...topic].map with [...topic.topics].map .尝试用[...topic.topics].map替换[...topic].map [...topic.topics].map

edit Sorry, I didn't see that the topic itself is an arr of objs, so it should be: [...topic[0].topics].map .编辑对不起,我没有看到topic本身是[...topic[0].topics].map的 arr,所以它应该是: [...topic[0].topics].map

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

相关问题 如何在不改变数组的情况下更新此状态? - How can I update this state without mutating the array? 如何在不变异的情况下更新对象数组的嵌套数组的状态 - How to update state of nested array of array of objects without mutating 如何存储以前的值而不是将值存储在反应状态的对象数组中 - How can I store previous values instead of storing the value in array of objects in react state 如何更新处于组件状态的对象数组? - How do I update an array of objects in component state? 如何在发生更改事件时正确更新状态,类型为type = range,它提供了先前的状态 - How can I update the state correctly on change event for form type=range, it gives the previous state 在 React redux 对象的状态数组中,我无法更新它创建的状态错误在调度之间检测到状态突变 - In React redux state array of objects i can't update the state it creates error A state mutation was detected between dispatches 如何更新对象的反应状态数组 - How to update react state array of objects 如何更新对象数组中的特定状态? - How to update specific state in array of objects? 如何在对象数组中使用 usestate 更新 state? - How to update state with usestate in an array of objects? 反应。 如何用以前的状态更新状态? - React. How to update the state with previous state?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM