簡體   English   中英

反應鈎子:如何使用 object 更新 state

[英]React hooks: How do I update state with object

我有 3 個這樣的組件,我如何在 App 組件中更新 state

我如何更新計數器組件中的 state onclick

import React, { useState } from 'react'
import Header from './components/Header'
import Counters from './components/Counters'

const App = () => {
  const initialCounters = [
    { id: 1, value: 0 },
    { id: 2, value: 0 },
    { id: 3, value: 0 },
    { id: 4, value: 0 },
  ]
  const [counters, setCounters] = useState(initialCounters)

  const onIncrement = (counter) => {
    console.log(counter)
  }

  return (
    <>
      <Header totalCounters={counters.length} />
      <main className='container'>
        <Counters counters={counters} onIncrement={onIncrement} />
      </main>
    </>
  )
}

export default App

在您的 Counters 組件中,當您調用 OnIncrement 方法時,您需要將其 id 作為參考傳遞。

然后在您的 OnIncrement 中執行此操作

  const onIncrement = (counterId) => {
    const updatededCounters = counters.map((counter) => {
     if(counter.id === counterId){
      counter.value++
      return counter     
      }
      return counter
     })
     setCounters(updatededCounters)
  }

只是為了在您的 Counters 組件中清楚

import React from "react";

const Counters = ({ counters, onIncrement }) => {
  return (
    <>
      {counters.map((counter) => (
        <div key={counter.id}>
          <p>My counter : {counter.value}</p>
          <button onClick={() => onIncrement(counter.id)}>Increment</button>
        </div>
      ))}
    </>
  );
};

父組件的完整代碼

import React, { useState } from "react";
import Counters from "./Counters";

const App = () => {
  const initialCounters = [
    { id: 1, value: 0 },
    { id: 2, value: 0 },
    { id: 3, value: 0 },
    { id: 4, value: 0 }
  ];
  const [counters, setCounters] = useState(initialCounters);
  const onIncrement = (counterId) => {
    const updatededCounters = counters.map((counter) => {
      if (counter.id === counterId) {
        counter.value++;
        return counter;
      }
      return counter;
    });
    setCounters(updatededCounters);
  };

  return (
    <>
      <main className="container">
        <Counters counters={counters} onIncrement={onIncrement} />
      </main>
    </>
  );
};

export default App;

Codesandbox 鏈接: https://codesandbox.io/s/sad-chebyshev-l4hez?file=/src/App.js:0-725

解釋

我所做的 onIncrement 方法很簡單:我將創建一個新數組,其中包含我想在其中編輯的值,然后我將使用這個新數組設置 state。

在.map()中,計數器的每個實例都將被循環,因此對於每個實例,我檢查其中一個是否是我要更新的那個(與我作為參數接收的counterId相同的id)

如果是這樣,我編輯當前計數器的值,然后返回計數器實例以允許循環繼續到下一個。

當計數器 id 與收到的 counterId 不同時,我只返回計數器而不做任何修改。

所以最后,你會得到相同的值數組,除了你增加的特定計數器,你會看到它的值更新了一個計數

I advice you to read some documentation about.map() function since it's really used in react: https://fr.reactjs.org/docs/lists-and-keys.html

And aswell you coud look into Object.keys() beceause it's often used with.map() aswell if you need to loop through object properties: https://reedbarger.com/how-to-transform-javascript-objects-the-對象鍵值條目的冪/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM