简体   繁体   English

在 React State 中使用原型

[英]Using Prototypes in React State

I'm trying to use prototypes to make looking up data from a deeply nested object easier.我正在尝试使用原型来更轻松地从深度嵌套的 object 中查找数据。 The issue is, when I use lodash's cloneDeep function the prototype chain is broken ( I'm pretty sure ).问题是,当我使用 lodash 的cloneDeep function 时,原型链已损坏(我很确定)。 I'm using the cloneDeep function to make sure not to mutate the state directly.我正在使用cloneDeep function 以确保不直接突变 state。

Before waisting anyone's time with some of the code from the project, is this an okay practice?在用项目中的一些代码浪费任何人的时间之前,这是一个好的做法吗? Is it correct to do something the following or should prototypes be avoided when storing objects in state?在 state 中存储对象时,执行以下操作是否正确或应避免使用原型?

const parent = { a: { b: { c: null }}}
const child = Object.create(parent)
parent.a.b.c = child

this.setState({ parent }) 

Thank you in advance for the help:)提前感谢您的帮助:)

I would second-take any deeply nested abstraction used as state.我会选择任何用作 state 的深度嵌套抽象。 Your state should be as flat as possible.您的 state尽可能平坦。 Nesting makes for really buggy code, and updating becomes a monumental task.嵌套会产生非常错误的代码,更新成为一项艰巨的任务。

constructor() {
    this.state = {foo: 'bar', a: 1, b: 2}
}

handleEvent(event) {
    this.setState({ ...this.state, foo: event.target.value })
}

render() {
    const { foo, a, b } = this.state
    // ...
}

This isn't really the direction React is moving though.不过,这并不是 React 真正的发展方向。 I would suggest having a look at the latest release notes.我建议查看最新的发行说明。

a) I'd suggest to use typescript instead of proptypes. a)我建议使用 typescript 而不是 proptypes。 It's more powerful and efficient.它更强大、更高效。

b) You don't need lodash to deep clone an object. b) 您不需要 lodash 来深度克隆 object。 Just do:做就是了:

 const objectA = {name: "Joe", age: 44} const clonedObjectA = {...objectA} // mutate clonedObject clonedObjectA.name= "Paul", console.log("objectA", objectA) // original untouched console.log("clonedObjectA", clonedObjectA) // new Object mutated

Then you can perform mutations on clonedObjectA without worrying about objectA.然后,您可以在clonedObjectA上执行突变,而不必担心 objectA。

c) when mutating a state, you can simply use prevState like this: c) 当改变 state 时,您可以像这样简单地使用 prevState:

 const [state, setState] = useState({}) const mutateState = (key, value) => { setState(prevState=> ({...prevState, key: value})) }

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

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