简体   繁体   English

反应钩子:如何使用 object 更新 state

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

I have 3 components like this, how I update state in App component我有 3 个这样的组件,我如何在 App 组件中更新 state

How I update state onclick in Counter component我如何更新计数器组件中的 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

In your Counters component when you call the OnIncrement method you need to pass it's id as reference.在您的 Counters 组件中,当您调用 OnIncrement 方法时,您需要将其 id 作为参考传递。

Then in your OnIncrement you do this然后在您的 OnIncrement 中执行此操作

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

Just to be clear in your Counters component只是为了在您的 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>
      ))}
    </>
  );
};

Full code for the parent component父组件的完整代码

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 link: https://codesandbox.io/s/sad-chebyshev-l4hez?file=/src/App.js:0-725 Codesandbox 链接: https://codesandbox.io/s/sad-chebyshev-l4hez?file=/src/App.js:0-725

Explanation解释

What i do the onIncrement method is simple: i will create a new array with values i want to edit inside of it, then i'll set the state with this new array.我所做的 onIncrement 方法很简单:我将创建一个新数组,其中包含我想在其中编辑的值,然后我将使用这个新数组设置 state。

In the.map() Each instance of counter will be looped, so for each instance i check if one of them is the one im looking for to update (with the same id as the counterId i receive as parameter)在.map()中,计数器的每个实例都将被循环,因此对于每个实例,我检查其中一个是否是我要更新的那个(与我作为参数接收的counterId相同的id)

If so, i edit the value of the current counter and then return the counter instance to allow the loop to continue to the next one.如果是这样,我编辑当前计数器的值,然后返回计数器实例以允许循环继续到下一个。

When the counter id is not the same as the counterId received, i just return the counter without any modification.当计数器 id 与收到的 counterId 不同时,我只返回计数器而不做任何修改。

So at the end, you will get the same array of values, exepct for the specific counter you incremented where you will see it's value updated by one count所以最后,你会得到相同的值数组,除了你增加的特定计数器,你会看到它的值更新了一个计数

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 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-power-of-objectkeys-values-entries/ 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