简体   繁体   English

使用上下文 API (React.js) 仅更改 state object 中的特定键

[英]Using context API (React.js) to change only a particular key in state object

I am using context API in react for managing state.我正在使用上下文 API 来管理 state。 For this I have created a file AppContext.js where I have created context and Provider:为此,我创建了一个文件AppContext.js ,在其中创建了上下文和提供程序:

import { useState, createContext } from "react";

export const AppContext = createContext();

export const AppProvider = (props) => {
   const [appdata, setAppdata] = useState({
      data1: "this is data1",
      data2: "this is data2",
   });

   return (
      <AppContext.Provider value={[appdata, setAppdata]}>
         {props.children}
      </AppContext.Provider>
   );
};

I have imported this Provider in the parent component of the app ie App.js .我已将此 Provider 导入应用程序的父组件中,即App.js Also I have wrapped the <AppChild/> component in the Provider.此外,我将<AppChild/>组件包装在 Provider 中。

import AppChild from "./AppChild";
import { AppProvider } from "./AppContext";

const App = () => {
   return (
      <AppProvider>
         <div className="App">hello</div>
         <AppChild />
      </AppProvider>
   );
};

export default App;

Now from AppChild component, I only needed to update the data1 key of my state.现在从AppChild组件,我只需要更新我的 state 的data1键。 For this I have created a button with a onClick through which I will be changing my state.为此,我创建了一个带有onClick的按钮,通过它我将更改我的 state。 I have used to following code in AppChild.js for this:为此,我习惯于在AppChild.js中使用以下代码:

import { useContext } from "react";
import { AppContext } from "./AppContext";

const AppChild = () => {
   const [appdata, setAppdata] = useContext(AppContext);
   return (
      <div>
         <h3 style={{ color: "red" }}>Data for Appchild: {appdata.data1}</h3>
         <button
            onClick={() =>
               setAppdata((prev) => {
                  prev.data1 = "updated data1";
                  return prev;
               })
            }
         >
            click to change
         </button>
      </div>
   );
};

export default AppChild;

But when I click the button, the text inside the <h3> block is not changing.但是当我单击按钮时, <h3>块内的文本没有改变。 Although when I change the whole state by passing the whole object directly to setAppdata as shown below,虽然当我通过将整个 object 直接传递给setAppdata来更改整个 state 时,如下所示, 新代码

This way the state updates successfully.这样 state 更新成功。 Why is the first method not working where I only wanted to change the data1 key?为什么我只想更改data1键的第一种方法不起作用?

You are updating state in wrong way so it is not working.您正在以错误的方式更新 state,因此它无法正常工作。 This is how you should update state这就是你应该如何更新 state

<button
 onClick={() =>
   setAppdata((prevState) => ({
     ...prevState,
     data1: "Your New Data"
        }))
      }
    >
        click to change
      </button>     

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM