简体   繁体   English

React 最佳实践:在组件中拥有除 `state` 之外的属性

[英]React Best Practices: Having properties other than `state` in a component

I'm reviewing a React Component and it contains a state property as well as an allData property.我正在查看一个 React 组件,它包含一个state属性以及一个allData属性。

To follow best practice, shouldn't allData be a part of state ?为了遵循最佳实践, allData state一部分吗?

constructor(props) {
    super(props);

    this.allData = [];
    this.state = {
      allDisplayedData: [],
      allRowsCount: -1,
      favData: [],
      favRowsCount: -1,
    };

    this.searchAll = this.searchAll.bind(this);
    this.handleCellClick = this.handleCellClick.bind(this);
  }

If you want to make the array part of state, then yes, if no, then no.如果你想让数组成为 state 的一部分,那么是,如果不是,那么不是。

If you want the component to re-render on changing it, then it needs to be in state, otherwise put it wherever.如果您希望组件在更改时重新渲染,那么它需要在 state 中,否则放在任何地方。 Any instance variables other than this.state aren't part of React's control, so they don't have the same ability to set using setState.除了this.state的任何实例变量都不是 React 控制的一部分,因此它们没有使用 setState 设置的相同能力。 This means that they don't re-render the component like the state does.这意味着它们不会像 state 那样重新渲染组件。

Essentially, it depends on what you do with it and how you want to work with it.本质上,这取决于你用它做什么以及你想如何使用它。

I tend to use this pattern for things like cancelTokens and intervalIds and other data I might need later, but don't need as part of the state because it's only needed in unmount or update but not in the render itself.我倾向于将此模式用于cancelTokens 和intervalIds 以及我以后可能需要的其他数据,但不需要作为state 的一部分,因为它仅在卸载或更新时需要,而不是在渲染本身中。

If it's needed in the render, you should have it in state or be prepared to deal with the component not rendering when it's updated.如果在渲染中需要它,您应该将它放在 state 中,或者准备好处理更新时不渲染的组件。

Other than the two previous detailed answers, I found the following statement at https://reactjs.org/docs/state-and-lifecycle.html除了前面两个详细的答案,我在https://reactjs.org/docs/state-and-lifecycle.html找到了以下语句

While this.props is set up by React itself and this.state has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn't participate in the data flow (like a timer ID).虽然 this.props 由 React 自己设置,并且 this.state 具有特殊含义,但如果您需要存储不参与数据流的内容(如计时器 ID )。

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

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