我有一个状态变量
authInfo:
const [authInfo, setAuthinfo] = useState(null)
数据从authInfo状态显示如下:
{
data:
id:
email:
full_name:
authorities: [{label: "admin", value: 1}, {label: "canEdit", value: 2}]
}
然后我有另一个数组。
const newAuthorities = [{label: 'canApprove', value 2}, {label: 'canDissaprove', value2}]
我希望将其存储在新的状态变量中,并复制旧的authInfo,其值将权限替换为newAuth变量。
这是预期的输出
{
data:
id:
email:
full_name:
authorities: [{label: 'canApprove', value 2}, {label: 'canDissaprove', value2}]
}
如何在另一个处于可变状态的状态下将newsAuthorities值替换为authorities值?
谢谢!
答案 0 :(得分:0)
const newAuthorities = [{label: 'canApprove', value 2}, {label: 'canDissaprove', value2}]
const data = {...authInfo}
data.authorities = newAuthorities
setAuthinfo(data)
答案 1 :(得分:0)
// Get a hook function
const {useState} = React;
const Auth = () => {
const authBase = {
data: null,
id: null,
email:null,
full_name: null,
authorities: [{label: "admin", value: 1}, {label: "canEdit", value: 2}]
}
const newAuthorities = [{label: 'canApprove', value: 2}, {label: 'canDissaprove', value: 2}]
const [authInfo, setAuthInfo] = useState(authBase)
const update = () => {
setAuthInfo({ ...authInfo, authorities: newAuthorities })
}
return (
<div>
<button onClick={update}>
Update
</button>
<pre>{JSON.stringify(authInfo, false, 2)}</pre>
</div>
);
};
// Render it
ReactDOM.render(
<Auth />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>