Javascript React.js上下文API:如何在维护其他值对的同时只更新对象的值对?
我正在使用React开发一个web应用程序,并使用contextapi跨不同层次结构的多个组件存储一些信息。我正在App.js上存储一个如下所示的对象:Javascript React.js上下文API:如何在维护其他值对的同时只更新对象的值对?,javascript,reactjs,react-context,Javascript,Reactjs,React Context,我正在使用React开发一个web应用程序,并使用contextapi跨不同层次结构的多个组件存储一些信息。我正在App.js上存储一个如下所示的对象: /* import Userinfo from './context/Userinfo' */ function App() { const [userinfo, setuserinfo] = useState({id: some_id, username: some_username, profile_picture:
/*
import Userinfo from './context/Userinfo'
*/
function App() {
const [userinfo, setuserinfo] = useState({id: some_id, username: some_username, profile_picture: some_profile_picture})
/*
*/
}
然后在更深层次的组件上使用上下文,如下所示:
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})
}
/////////
问题是,如何只更新一对存储对象?例如,假设我只想更新“id”部分,同时保持其他字段不变。这样做的语法是什么
提前多谢 方法是复制对象,然后更改新对象的字段
const userinfo = {
id: new_id,
username: new_username,
profile_picture: new_profile_picture
}
const newUserInfo = {
...userInfo, // deep copy userInfo into newUserInfo (
id: 'new_id' // update id to 'new_id', other fields are not changed
}
// update userInfo
setUserInfo(newUserInfo)
我在这里创建newUserInfo
的方法是将以下几行组合成一行
// create a copy of userInfo
const newUserInfo = {
...userInfo,
}
// change the id of the the new object
newUserInfo.id = 'new_id'
这样做的目的是复制对象,然后更改新对象的字段
const userinfo = {
id: new_id,
username: new_username,
profile_picture: new_profile_picture
}
const newUserInfo = {
...userInfo, // deep copy userInfo into newUserInfo (
id: 'new_id' // update id to 'new_id', other fields are not changed
}
// update userInfo
setUserInfo(newUserInfo)
我在这里创建newUserInfo
的方法是将以下几行组合成一行
// create a copy of userInfo
const newUserInfo = {
...userInfo,
}
// change the id of the the new object
newUserInfo.id = 'new_id'
对我来说,这个问题是关于
useState()
API而不是useContext()
从const[state,setState]=useState()
返回的setState()
函数,在您的示例中是setuserinfo()
函数,实际上有另一个将函数作为参数的签名
调用时,该函数作为参数在前一状态下传递。您只需输入prevState
即可保留旧的对,并仅更改id
字段:
const infoupdate = () => {
setuserinfo(prevState => ({
...prevState,
id: new_id,
}))
}
对我来说,这个问题是关于
useState()
API而不是useContext()
从const[state,setState]=useState()
返回的setState()
函数,在您的示例中是setuserinfo()
函数,实际上有另一个将函数作为参数的签名
调用时,该函数作为参数在前一状态下传递。您只需输入prevState
即可保留旧的对,并仅更改id
字段:
const infoupdate = () => {
setuserinfo(prevState => ({
...prevState,
id: new_id,
}))
}