在 React 中存储数据 [英] Storing data in React

查看:84
本文介绍了在 React 中存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是 React 的新手,无法选择在这种情况下存储数据的最佳方式是什么:我有一个包含一些输入的表单,我需要在提交时对来自这些输入的所有数据执行一些操作.所有输入都存储在一个组件中.所以,我只需要在提交时获取所有数据.现在我正在尝试选择存储这些数据的最佳方式.我看到两种方式:

I'm actually new to React, and can't choose, what is the best way to store data in a situation like this: I have a form with some inputs, and I need to do some actions with all data from these inputs on submit. All inputs are stored in one Component. So, I need to get all the data only on submit. And now I'm trying to choose the best way to store this data. I see 2 ways:

  • 在状态中存储数据.但正如 React Docs 描述的那样:

  • Storing data in the state. But as React Docs describes:

只有需要渲染的数据才能存储在状态中."

"Only data which need to render may store in the state."

但我不需要这些数据进行渲染,我只需要在提交时使用它.

But I don't need this data for render, I need to work with this only on submit.

存储为类变量.对我来说看起来不错,因为当我使用状态,我需要调用 setState(),它会触发渲染(我不需要),或者 this.state.data = ....但是 React Docs 说:

Storing as class variables. It looks good for me, because when i using state, i need to call setState(), which trigger render(which i don't need), or this.state.data = ....But React Docs says that:

您只能在构造函数中直接更改状态."

"You may change state directly only in constructor."

那么,这些方法中哪些更好,为什么?

So, which of these ways are better and why?

推荐答案

我认为你想多了,只是坚持使用受控组件并通过状态管理你的表单数据.

I think you're overthinking it, just stick with controlled components and manage your form data through state.

但是,如果您真的不想使用受控组件,因为您不想调用 render 方法,那么您不必这样做.

However, if you really don't want to use controlled components because you don't want the render method to be called then you don't have to.

这是因为表单元素在 React 中的工作方式与其他 DOM 元素略有不同,因为在 HTML 中,表单元素例如