React.js Context API:如何仅更新对象的值对,同时维护其他对?

J.K*_*.Ko 3 javascript reactjs react-context

我正在使用 React 开发一个 Web 应用程序,并使用上下文 API 来跨不同层次结构的多个组件存储一些信息。我正在 App.js 上存储如下所示的对象:

 /*
 import Userinfo from './context/Userinfo'
 */

 function App() {
      const [userinfo, setuserinfo] = useState({id: some_id, username: some_username, profile_picture: some_profile_picture})
 /*
 */
 }
Run Code Online (Sandbox Code Playgroud)

然后在更深的组件上使用上下文,如下所示:

 import Userinfo from '../context/Userinfo';

 function Profile() {
      const {userinfo, setuserinfo)=useContext(Userinfo);

      const infoupdate = () => {  //Function to update the userinfo stored by context API
           setuserinfo({id: new_id, username: new_username, profile_picture: new_profile_picture})
      }
     /////////
Run Code Online (Sandbox Code Playgroud)

问题是,如何只更新一对存储的对象?例如,假设我只想更新“id”部分,同时保持其他字段相同。执行此操作的语法是什么?

预先非常感谢!

hac*_*ape 5

对我来说这个问题是关于useState()API 而不是useContext().

setState()从 返回的函数(const [state, setState] = useState()在您的示例中为setuserinfo()函数)实际上有另一个接受函数作为参数的签名。

调用时,该函数会以先前的状态作为参数传递。您可以简单地扩展它prevState以保留旧对,并仅更改id字段:

const infoupdate = () => {
    setuserinfo(prevState => ({
        ...prevState,
        id: new_id,
    }))
}
Run Code Online (Sandbox Code Playgroud)