最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to maintain previous data and current data in react usestate in react-native or reactjs? - Stack Overflow

programmeradmin0浏览0评论

Currently i am learning reactjs. I want to store my previous data and uping data in usestate . IS there any trick for that ?

For example : Firstly i input "A" after that i input "B". I want A and B are stored in usestate even when i add new data in it

Currently i am learning reactjs. I want to store my previous data and uping data in usestate . IS there any trick for that ?

For example : Firstly i input "A" after that i input "B". I want A and B are stored in usestate even when i add new data in it

Share Improve this question asked Jun 18, 2022 at 11:47 TaehyungTaehyung 531 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

It's very easy. You can use my code snippet. With the help of this you can store your previous data and uping data as well.

Method 1:

const [arrayOfObjs, handleObjSelection] = useState([]);
// on a buttton for example
<button
  onClick={selectedObj => handleObjSelection(
              prevSelected => [...prevSelected, selectedObj],
          ))}
>

Method 2:

const [ store, setStore] = useState([]);
 .....

 setStore(...store, upingData);

Here Uping Data is the data which you want to add in the useState. It can be store as well. Like:

const [ store, setStore] = useState([]);
     .....
    
     setStore(...store, store);

I would use object state for this then you can keep both state. Here is the working version https://codesandbox.io/embed/frosty-bird-hg3izs?fontsize=14&hidenavigation=1&theme=dark

import { useState } from "react";

export default function App() {
  const [obj, setObj] = useState({previous: '', current: ''})

  const handleChange = (e) => {
    setObj({previous: obj.current, current: e.target.value})
  }
  return (
    <div className="App">
      <input value={obj.current} onChange={(e) => handleChange(e)} />
      <p>I am previous {obj.previous} </p>
      <p>I am current {obj.current} </p>
    </div>
  );
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论