简体   繁体   English

将状态嵌套在React中是不好的做法吗?

[英]Is it bad practice to nest states in React?

I've been working on a project and have gotten help from a couple of people. 我一直在从事一个项目,并得到了几个人的帮助。 One of them told me it would be a better idea to nest my states, and so I did. 其中一个告诉我,嵌套我的国家是一个更好的主意,所以我做到了。 However, when I got help from someone else they had told me that nesting states is not a good idea and that I should avoid doing it. 但是,当我从别人那里得到帮助时,他们告诉我嵌套状态不是一个好主意,我应该避免这样做。 I don't have a lot of experience with this at all but I would like to do it the better/most practical way possible. 我完全没有很多经验,但是我想以更好/最实用的方式来做。 Does anyone have any input? 有人有任何输入吗?

Here's an example of what I meant by nested states: 这是我所说的嵌套状态的示例:

constructor(props){
    super(props);
    this.state = {
        someGroup = [{
            somePartA: "",
            somePartB: [],
            someKey: uuid()
        }],
        somethingElse = "",
        anotherOne = "",
    }
}

And here's what I mean by not nested 这就是我不嵌套的意思

constructor(props){
    super(props);
    this.state = {
        somePartA: "",
        somePartB: [],
        someKey: uuid(),
        somethingElse = "",
        anotherOne = "",
    }
}

Thanks in advance! 提前致谢!

It's generally a good idea to keep your state shallow. 通常,保持状态较浅是个好主意。

If you have a complex application, it's an even better idea to limit state to UI concerns and use a state container outside of the component like Redux, especially when the data you're keeping in state is more application data than local component concerns. 如果您有一个复杂的应用程序,那么最好将状态限制在UI问题上,并在像Redux这样的组件外部使用状态容器,尤其是当您保持状态的数据比本地组件问题更多时,是应用程序数据。

This is potentially a big topic with loads of opinion. 这可能是一个充满观点的大话题。 If you haven't yet I would read up on React state design. 如果您还没有,我会读一下React状态设计。 Here are some articles. 这里有一些文章。 Keep in mind there's no single answer. 请记住,没有一个答案。 But these should help you build a foundation. 但是这些应该可以帮助您建立基础。

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

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