我正在尝试使用这样的嵌套属性来组织我的状态:
this.state = {
someProperty: {
flag:true
}
}
但是像这样更新状态,
this.setState({ someProperty.flag: false });
不起作用。如何正确地做到这一点?
我正在尝试使用这样的嵌套属性来组织我的状态:
this.state = {
someProperty: {
flag:true
}
}
但是像这样更新状态,
this.setState({ someProperty.flag: false });
不起作用。如何正确地做到这一点?
为了setState
嵌套对象,您可以遵循以下方法,因为我认为 setState 不处理嵌套更新。
var someProperty = {...this.state.someProperty}
someProperty.flag = true;
this.setState({someProperty})
这个想法是创建一个虚拟对象对其执行操作,然后用更新的对象替换组件的状态
现在,展开运算符只创建对象的一级嵌套副本。如果您的状态高度嵌套,例如:
this.state = {
someProperty: {
someOtherProperty: {
anotherProperty: {
flag: true
}
..
}
...
}
...
}
您可以 setState 在每个级别使用扩展运算符,例如
this.setState(prevState => ({
...prevState,
someProperty: {
...prevState.someProperty,
someOtherProperty: {
...prevState.someProperty.someOtherProperty,
anotherProperty: {
...prevState.someProperty.someOtherProperty.anotherProperty,
flag: false
}
}
}
}))
然而,随着状态变得越来越嵌套,上述语法变得越来越难看,因此我建议您使用immutability-helper
包来更新状态。
有关如何使用更新状态的信息,请参阅此答案immutability-helper
。
写在一行
this.setState({ someProperty: { ...this.state.someProperty, flag: false} });
有时直接的答案不是最好的:)
简洁版本:
这段代码
this.state = {
someProperty: {
flag: true
}
}
应该简化为
this.state = {
somePropertyFlag: true
}
长版:
目前你不应该在 React 中使用嵌套状态。因为 React 不适合使用嵌套状态,并且这里提出的所有解决方案看起来都是 hack。他们不使用框架,而是与之抗争。他们建议编写不太清晰的代码,用于对某些属性进行分组的可疑目的。因此,它们作为挑战的答案非常有趣,但实际上毫无用处。
让我们想象一下以下状态:
{
parent: {
child1: 'value 1',
child2: 'value 2',
...
child100: 'value 100'
}
}
如果你只改变一个值会发生什么child1
?React 不会重新渲染视图,因为它使用浅比较并且它会发现parent
属性没有改变。顺便说一句,直接改变状态对象通常被认为是一种不好的做法。
所以你需要重新创建整个parent
对象。但在这种情况下,我们会遇到另一个问题。React 会认为所有的孩子都改变了他们的价值观,并会重新渲染所有的孩子。当然,这对性能不利。
仍然可以通过编写一些复杂的逻辑来解决这个问题,shouldComponentUpdate()
但我更愿意在这里停下来并使用简短版本中的简单解决方案。
React 中的嵌套状态是错误的设计
阅读这个出色的答案。
这个答案背后的推理:
React 的 setState 只是一个内置的便利,但你很快就会意识到它有它的局限性。使用自定义属性和智能使用可以
forceUpdate
为您提供更多。例如:class MyClass extends React.Component { myState = someObject inputValue = 42 ...
例如,MobX 完全抛弃状态并使用自定义的可观察属性。
在 React 组件中使用 Observables 而不是 state。
还有另一种更短的方法来更新任何嵌套属性。
this.setState(state => {
state.nested.flag = false
state.another.deep.prop = true
return state
})
this.setState(state => (state.nested.flag = false, state))
注意:这是逗号运算符 ~MDN,请在此处查看实际操作 (Sandbox)。
它类似于(尽管这不会改变状态参考)
this.state.nested.flag = false
this.forceUpdate()
有关此上下文中的细微差别,forceUpdate
请setState
参阅链接的示例和沙箱。
当然这是滥用一些核心原则,因为state
应该是只读的,但是由于您立即丢弃旧状态并用新状态替换它,所以完全可以。
即使包含状态的组件将正确更新和重新渲染(除了这个问题),道具也将无法传播给孩子(请参阅下面的 Spymaster 评论)。仅当您知道自己在做什么时才使用此技术。
例如,您可以传递一个已更改的平面道具,该道具可以轻松更新和传递。
render(
//some complex render with your nested state
<ChildComponent complexNestedProp={this.state.nested} pleaseRerender={Math.random()}/>
)
现在即使 complexNestedProp 的参考没有改变(shouldComponentUpdate)
this.props.complexNestedProp === nextProps.complexNestedProp
每当父组件更新时,组件都会重新渲染,这是在调用之后this.setState
或this.forceUpdate
在父组件中的情况。
使用嵌套状态和直接改变状态是危险的,因为不同的对象可能(有意或无意地)持有对状态的不同(旧)引用,并且可能不一定知道何时更新(例如在使用时PureComponent
或是否shouldComponentUpdate
实现返回时false
)或者是旨在显示旧数据,如下例所示。
想象一个应该呈现历史数据的时间线,改变手下的数据将导致意外行为,因为它也会改变以前的项目。
无论如何,在这里您可以看到Nested PureChildClass
由于道具未能传播而没有重新渲染。
如果您使用的是 ES2015,您可以访问 Object.assign。您可以按如下方式使用它来更新嵌套对象。
this.setState({
someProperty: Object.assign({}, this.state.someProperty, {flag: false})
});
您将更新的属性与现有的属性合并,并使用返回的对象来更新状态。
编辑:向分配函数添加了一个空对象作为目标,以确保状态不会像 carkod 指出的那样直接发生突变。
const newState = Object.assign({}, this.state);
newState.property.nestedProperty = "new value";
this.setState(newState);
我们使用 Immer https://github.com/mweststrate/immer来处理这类问题。
刚刚在我们的一个组件中替换了这段代码
this.setState(prevState => ({
...prevState,
preferences: {
...prevState.preferences,
[key]: newValue
}
}));
有了这个
import produce from 'immer';
this.setState(produce(draft => {
draft.preferences[key] = newValue;
}));
使用 immer,您可以将状态作为“普通对象”处理。魔术发生在代理对象的幕后。
有很多图书馆可以帮助解决这个问题。例如,使用immutability-helper:
import update from 'immutability-helper';
const newState = update(this.state, {
someProperty: {flag: {$set: false}},
};
this.setState(newState);
使用lodash/fp设置:
import {set} from 'lodash/fp';
const newState = set(["someProperty", "flag"], false, this.state);
使用lodash/fp合并:
import {merge} from 'lodash/fp';
const newState = merge(this.state, {
someProperty: {flag: false},
});
尽管您询问了基于类的 React 组件的状态,但 useState 挂钩也存在同样的问题。更糟糕的是:useState 挂钩不接受部分更新。因此,当引入 useState 挂钩时,这个问题变得非常重要。
我决定发布以下答案,以确保问题涵盖使用 useState 挂钩的更现代场景:
如果你有:
const [state, setState] = useState({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })
您可以通过克隆当前数据并修补所需的数据段来设置嵌套属性,例如:
setState(current => { ...current, someProperty: { ...current.someProperty, flag: false } });
或者您可以使用 Immer 库来简化对象的克隆和修补。
或者您可以使用Hookstate 库(免责声明:我是作者)来完全简单地管理复杂(本地和全局)状态数据并提高性能(阅读:不用担心渲染优化):
import { useStateLink } from '@hookstate/core'
const state = useStateLink({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })
获取要渲染的字段:
state.nested.someProperty.nested.flag.get()
// or
state.get().someProperty.flag
设置嵌套字段:
state.nested.someProperty.nested.flag.set(false)
这是 Hookstate 示例,其中状态深度/递归嵌套在树状数据结构中。
这是此线程中给出的第一个答案的变体,不需要任何额外的包、库或特殊功能。
state = {
someProperty: {
flag: 'string'
}
}
handleChange = (value) => {
const newState = {...this.state.someProperty, flag: value}
this.setState({ someProperty: newState })
}
为了设置特定嵌套字段的状态,您已经设置了整个对象。我通过创建一个变量来做到这一点,并首先使用 ES2015扩展运算符newState
将当前状态的内容传播到其中。然后,我用新值替换了 的值(因为我是在将当前状态传播到对象后设置的,所以当前状态中的字段被覆盖)。然后,我只需将状态设置为我的对象。this.state.flag
flag: value
flag
someProperty
newState
我使用了这个解决方案。
如果您有这样的嵌套状态:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
您可以声明复制当前状态并使用更改的值重新分配它的 handleChange 函数
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
这里是带有事件监听器的 html
<input type="text" onChange={this.handleChange} " name="friendName" />
尽管嵌套并不是你真正应该如何对待组件状态的方式,但有时对于单层嵌套来说很容易。
对于这样的状态
state = {
contact: {
phone: '888-888-8888',
email: 'test@test.com'
}
address: {
street:''
},
occupation: {
}
}
我使用的可重复使用的方法看起来像这样。
handleChange = (obj) => e => {
let x = this.state[obj];
x[e.target.name] = e.target.value;
this.setState({ [obj]: x });
};
然后只需为您要处理的每个嵌套传递 obj 名称...
<TextField
name="street"
onChange={handleChange('address')}
/>
创建状态的副本:
let someProperty = JSON.parse(JSON.stringify(this.state.someProperty))
对此对象进行更改:
someProperty.flag = "false"
现在更新状态
this.setState({someProperty})
我看到每个人都给出了基于类的组件状态更新解决方案,这是预期的,因为他要求这样做,但我试图为钩子提供相同的解决方案。
const [state, setState] = useState({
state1: false,
state2: 'lorem ipsum'
})
现在,如果您只想更改嵌套对象键state1,则可以执行以下任何操作:
过程 1
let oldState = state;
oldState.state1 = true
setState({...oldState);
过程 2
setState(prevState => ({
...prevState,
state1: true
}))
我最喜欢过程2。
尚未提及的另外两个选项:
为了使事情通用,我研究了@ShubhamKhatri 和@Qwerty 的答案。
状态对象
this.state = {
name: '',
grandParent: {
parent1: {
child: ''
},
parent2: {
child: ''
}
}
};
输入控件
<input
value={this.state.name}
onChange={this.updateState}
type="text"
name="name"
/>
<input
value={this.state.grandParent.parent1.child}
onChange={this.updateState}
type="text"
name="grandParent.parent1.child"
/>
<input
value={this.state.grandParent.parent2.child}
onChange={this.updateState}
type="text"
name="grandParent.parent2.child"
/>
更新状态方法
setState 作为@ShubhamKhatri 的回答
updateState(event) {
const path = event.target.name.split('.');
const depth = path.length;
const oldstate = this.state;
const newstate = { ...oldstate };
let newStateLevel = newstate;
let oldStateLevel = oldstate;
for (let i = 0; i < depth; i += 1) {
if (i === depth - 1) {
newStateLevel[path[i]] = event.target.value;
} else {
newStateLevel[path[i]] = { ...oldStateLevel[path[i]] };
oldStateLevel = oldStateLevel[path[i]];
newStateLevel = newStateLevel[path[i]];
}
}
this.setState(newstate);
}
setState 作为@Qwerty 的回答
updateState(event) {
const path = event.target.name.split('.');
const depth = path.length;
const state = { ...this.state };
let ref = state;
for (let i = 0; i < depth; i += 1) {
if (i === depth - 1) {
ref[path[i]] = event.target.value;
} else {
ref = ref[path[i]];
}
}
this.setState(state);
}
注意:以上这些方法不适用于数组
我非常重视围绕创建组件状态的完整副本已经表达的担忧。话虽如此,我强烈建议Immer。
import produce from 'immer';
<Input
value={this.state.form.username}
onChange={e => produce(this.state, s => { s.form.username = e.target.value }) } />
这应该适用于React.PureComponent
(即 React 的浅层状态比较),因为它Immer
巧妙地使用代理对象来有效地复制任意深度的状态树。与 Immutability Helper 等库相比,Immer 的类型安全性更高,非常适合 Javascript 和 Typescript 用户。
打字稿实用功能
function setStateDeep<S>(comp: React.Component<any, S, any>, fn: (s:
Draft<Readonly<S>>) => any) {
comp.setState(produce(comp.state, s => { fn(s); }))
}
onChange={e => setStateDeep(this, s => s.form.username = e.target.value)}
根据框架的标准,不确定这在技术上是否正确,但有时您只需要更新嵌套对象。这是我使用钩子的解决方案。
setInputState({
...inputState,
[parentKey]: { ...inputState[parentKey], [childKey]: value },
});
如果要动态设置状态
以下示例动态设置表单状态,其中状态中的每个键都是对象
onChange(e:React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
this.setState({ [e.target.name]: { ...this.state[e.target.name], value: e.target.value } });
}
我发现这对我有用,在我的情况下有一个项目表单,例如你有一个 id 和一个名称,我宁愿维护嵌套项目的状态。
return (
<div>
<h2>Project Details</h2>
<form>
<Input label="ID" group type="number" value={this.state.project.id} onChange={(event) => this.setState({ project: {...this.state.project, id: event.target.value}})} />
<Input label="Name" group type="text" value={this.state.project.name} onChange={(event) => this.setState({ project: {...this.state.project, name: event.target.value}})} />
</form>
</div>
)
让我知道!
stateUpdate = () => {
let obj = this.state;
if(this.props.v12_data.values.email) {
obj.obj_v12.Customer.EmailAddress = this.props.v12_data.values.email
}
this.setState(obj)
}
如果你在你的项目中使用 formik,它有一些简单的方法来处理这些东西。这是使用 formik 最简单的方法。
首先在 formik initivalues 属性或反应中设置初始值。状态
这里,初始值是在反应状态中定义的
state = {
data: {
fy: {
active: "N"
}
}
}
initiValues
为 formik属性内的 formik 字段定义上述 initialValues
<Formik
initialValues={this.state.data}
onSubmit={(values, actions)=> {...your actions goes here}}
>
{({ isSubmitting }) => (
<Form>
<Field type="checkbox" name="fy.active" onChange={(e) => {
const value = e.target.checked;
if(value) setFieldValue('fy.active', 'Y')
else setFieldValue('fy.active', 'N')
}}/>
</Form>
)}
</Formik>
制作一个控制台来检查更新到的状态,string
而不是boolean
使用 formiksetFieldValue
函数来设置状态,或者使用 react 调试器工具来查看 formik 状态值的变化。
这显然不是正确或最好的方法,但在我看来它更清晰:
this.state.hugeNestedObject = hugeNestedObject;
this.state.anotherHugeNestedObject = anotherHugeNestedObject;
this.setState({})
然而,React 本身应该迭代思想嵌套对象并相应地更新状态和 DOM,而这还不存在。
您可以使用对象传播代码来做到这一点:
this.setState((state)=>({ someProperty:{...state.someProperty,flag:false}})
这将适用于更多嵌套属性
<input type="text" name="title" placeholder="add title" onChange={this.handleInputChange} />
<input type="checkbox" name="chkusein" onChange={this.handleInputChange} />
<textarea name="body" id="" cols="30" rows="10" placeholder="add blog content" onChange={this.handleInputChange}></textarea>
代码非常可读
处理程序
handleInputChange = (event) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
const newState = { ...this.state.someProperty, [name]: value }
this.setState({ someProperty: newState })
}
您应该将新状态传递给 setState。新状态的引用必须不同于旧状态。
所以试试这个:
this.setState({
...this.state,
someProperty: {...this.state.someProperty, flag: true},
})
这样的事情可能就足够了,
const isObject = (thing) => {
if(thing &&
typeof thing === 'object' &&
typeof thing !== null
&& !(Array.isArray(thing))
){
return true;
}
return false;
}
/*
Call with an array containing the path to the property you want to access
And the current component/redux state.
For example if we want to update `hello` within the following obj
const obj = {
somePrimitive:false,
someNestedObj:{
hello:1
}
}
we would do :
//clone the object
const cloned = clone(['someNestedObj','hello'],obj)
//Set the new value
cloned.someNestedObj.hello = 5;
*/
const clone = (arr, state) => {
let clonedObj = {...state}
const originalObj = clonedObj;
arr.forEach(property => {
if(!(property in clonedObj)){
throw new Error('State missing property')
}
if(isObject(clonedObj[property])){
clonedObj[property] = {...originalObj[property]};
clonedObj = clonedObj[property];
}
})
return originalObj;
}
const nestedObj = {
someProperty:true,
someNestedObj:{
someOtherProperty:true
}
}
const clonedObj = clone(['someProperty'], nestedObj);
console.log(clonedObj === nestedObj) //returns false
console.log(clonedObj.someProperty === nestedObj.someProperty) //returns true
console.log(clonedObj.someNestedObj === nestedObj.someNestedObj) //returns true
console.log()
const clonedObj2 = clone(['someProperty','someNestedObj','someOtherProperty'], nestedObj);
console.log(clonedObj2 === nestedObj) // returns false
console.log(clonedObj2.someNestedObj === nestedObj.someNestedObj) //returns false
//returns true (doesn't attempt to clone because its primitive type)
console.log(clonedObj2.someNestedObj.someOtherProperty === nestedObj.someNestedObj.someOtherProperty)
我知道这是一个老问题,但仍然想分享我是如何做到这一点的。假设构造函数中的状态如下所示:
constructor(props) {
super(props);
this.state = {
loading: false,
user: {
email: ""
},
organization: {
name: ""
}
};
this.handleChange = this.handleChange.bind(this);
}
我的handleChange
功能是这样的:
handleChange(e) {
const names = e.target.name.split(".");
const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
this.setState((state) => {
state[names[0]][names[1]] = value;
return {[names[0]]: state[names[0]]};
});
}
并确保您相应地命名输入:
<input
type="text"
name="user.email"
onChange={this.handleChange}
value={this.state.user.firstName}
placeholder="Email Address"
/>
<input
type="text"
name="organization.name"
onChange={this.handleChange}
value={this.state.organization.name}
placeholder="Organization Name"
/>
我使用减少搜索进行嵌套更新:
例子:
状态中的嵌套变量:
state = {
coords: {
x: 0,
y: 0,
z: 0
}
}
功能:
handleChange = nestedAttr => event => {
const { target: { value } } = event;
const attrs = nestedAttr.split('.');
let stateVar = this.state[attrs[0]];
if(attrs.length>1)
attrs.reduce((a,b,index,arr)=>{
if(index==arr.length-1)
a[b] = value;
else if(a[b]!=null)
return a[b]
else
return a;
},stateVar);
else
stateVar = value;
this.setState({[attrs[0]]: stateVar})
}
采用:
<input
value={this.state.coords.x}
onChange={this.handleTextChange('coords.x')}
/>
这是我的初始状态
const initialStateInput = {
cabeceraFamilia: {
familia: '',
direccion: '',
telefonos: '',
email: ''
},
motivoConsulta: '',
fechaHora: '',
corresponsables: [],
}
钩子或者你可以用状态(类组件)替换它
const [infoAgendamiento, setInfoAgendamiento] = useState(initialStateInput);
handleChange 的方法
const actualizarState = e => {
const nameObjects = e.target.name.split('.');
const newState = setStateNested(infoAgendamiento, nameObjects, e.target.value);
setInfoAgendamiento({...newState});
};
使用嵌套状态设置状态的方法
const setStateNested = (state, nameObjects, value) => {
let i = 0;
let operativeState = state;
if(nameObjects.length > 1){
for (i = 0; i < nameObjects.length - 1; i++) {
operativeState = operativeState[nameObjects[i]];
}
}
operativeState[nameObjects[i]] = value;
return state;
}
最后这是我使用的输入
<input type="text" className="form-control" name="cabeceraFamilia.direccion" placeholder="Dirección" defaultValue={infoAgendamiento.cabeceraFamilia.direccion} onChange={actualizarState} />
试试这个代码:
this.setState({ someProperty: {flag: false} });
如果对象列表中有多个项目,还有另一种选择:使用 this.state.Obj 将对象复制到变量(例如 temp),使用 filter() 方法遍历对象并获取特定元素您想更改为一个对象(将其命名为 updateObj)并将剩余的对象列表更改为另一个对象(将其命名为 restObj)。现在编辑要更新的对象的内容,创建一个新项目(比如 newItem)。然后调用 this.setUpdate() 并使用扩展运算符将新的对象列表分配给父对象。
this.state = {someProperty: { flag:true, }}
var temp=[...this.state.someProperty]
var restObj = temp.filter((item) => item.flag !== true);
var updateObj = temp.filter((item) => item.flag === true);
var newItem = {
flag: false
};
this.setState({ someProperty: [...restObj, newItem] });