本文共 8184 字,大约阅读时间需要 27 分钟。
react 左右互动
This is part of my “React for beginners” series on introducing React, its core features and best practices to follow. More articles are coming!
这是我的“初学者React”系列的一部分,该系列介绍了React,其核心功能和可遵循的最佳实践。 更多文章来了!
|
|
If you know — that’s great. Now, let’s give our components their own data.
如果您知道 ,那就太好了。 现在,让我们为组件提供自己的数据。
Disclaimer: This article focuses on React’s built-in state. Note that component state and Redux are not incompatible, as their purpose is different.
免责声明:本文重点介绍React的内置状态。 请注意,组件状态和Redux不兼容,因为它们的用途不同。
In my opinion, component state is specific to the component scope (for form completion). Besides, Redux state helps with sharing the same state among many components.
在我看来,组件状态特定于组件范围(用于表单完成)。 此外,Redux状态有助于在许多组件之间共享同一状态。
To learn states, let’s create a Question
component. It will display a yes/no question and ask for an answer.
要了解状态,我们创建一个Question
组件。 它将显示是/否问题并要求答案。
class Question extends React.Component { constructor(props) { // Init props and state super(props); this.state = { answered: false }; this.answerQuestion = this.answerQuestion.bind(this); } answerQuestion({target}){ // State update (user answers to the question) let answer = target.value === 'true' ? true : false; this.setState({ answered: true, answer }); } render() { // Component template in JSX if(this.state.answered) { returnYou already answered this question ({this.state.answer ? 'yes' : 'no'})
} return ({this.props.label}
); }}
Our Question
component contains only three functions:
我们的Question
组件仅包含三个功能:
constructor
for initialization (props and state),
初始化的constructor
函数(属性和状态),
answerQuestion
is a callback triggered when the user answers
answerQuestion
是用户回答时触发的回调
render
that you probably already know — it outputs the component’s template.
render
您可能已经知道的-它输出组件的模板。
This component has two distinct states. The question is not answered, or the question has an answer.
该组件具有两个不同的状态。 问题未回答,或者问题有答案。
Props are only used for the question label, and besides, the state’s purpose is far more interesting.
道具仅用于问题标签,此外,该州的目的更加有趣。
The state is the component memory which remembers if the question has an answer. If so, it also knows the answer.
状态是组件存储器,它记住问题是否有答案。 如果是这样,它也知道答案。
Using a state in a component is easy. You have to initialize the state and call setState
function whenever you want to update its content.
在组件中使用状态很容易。 每当您要更新其内容时,都必须初始化状态并调用setState
函数。
Imagine being a component. If your state changed, your reaction would be to check if you have to update your display.
想象一下成为一个组件。 如果状态发生变化,您的React将是检查是否必须更新显示。
That’s how it works. React calls shouldComponentUpdate
before calling render
(). This second function will generate the next Virtual DOM state ( talks about it).
这就是它的工作方式。 在调用render
之前,React调用shouldComponentUpdate
( )。 第二个函数将生成下一个虚拟DOM状态( 对此进行了讨论)。
class Survey extends React.Component { // Somewhere in constructor function this.state = { questions: [ 'Do you like bananas ?', 'Are you a developer ?' ] }; // Somewhere in render function this.state.questions.map(question =>)}
Components get props from other components. If those props change, then the component will update.
组件从其他组件获取道具。 如果这些道具发生变化,则组件将更新。
Actually, you already know how it works — but let’s take the example of a Survey
containing some Question
.
实际上,您已经知道它是如何工作的-但让我们以包含一些Question
的Survey
的示例为例。
The Survey
contains question labels in its state and gives it to Question
as a property.
Survey
包含处于其状态的问题标签,并将其作为属性提供给Question
。
When the Survey
updates its state (calls setState
), the render
function triggers. If so, it sends a request for Question
rendering (details in ).
当Survey
更新其状态(调用setState
)时,将触发render
功能。 如果是这样,它将发送一个Question
渲染请求( 详细信息)。
Decoupling the view and the rest of the code has always been a big concern among developers. That’s why most of the design patterns used in frameworks extend from the MVC pattern.
将视图与其余代码分离,一直是开发人员关注的大问题。 这就是为什么框架中使用的大多数设计模式都是从MVC模式扩展而来的。
If you use React with Redux, you already know the container pattern. Actually, it’s a built-in Redux feature through the connect function.
如果您将React与Redux一起使用,则您已经知道容器模式。 实际上,它是通过connect函数内置的Redux功能。
/* Question and QuestionContainer are both regular React components QuestionContainer renders a single Question component and provides access to redux stuff through props*/const QuestionContainer = connect(mapStateToProps, mapDispatchToProps)(Question);
It’s time to split the Question
component into two components.
现在是时候将Question
组件分为两个组件了。
Question
will be responsible for rendering props. This kind of component is called either functional, presentational, or a dumb component.
Question
将负责渲染道具。 这种组件称为功能组件,表示组件或哑组件。
QuestionContainer
will deal with state management.
QuestionContainer
将处理状态管理。
const Question = (props) =>{props.label}
class QuestionContainer extends React.Component { constructor(props) { super(props); this.state = { answered: false }; this.answerQuestion = this.answerQuestion.bind(this); } answerQuestion({target}){ let answer = target.value === 'true' ? true : false; this.setState({ answered: true, answer }); } render() { if(props.answered) { returnYou already answered this question (props.answer ? 'yes' : 'no'})
} // Here is the trick return}}
For comparison with the MVC design pattern, Question
is a View and QuestionContainer
is a Controller.
为了与MVC设计模式进行比较, Question
是View,而QuestionContainer
是Controller 。
Other components which need Question
will now use QuestionContainer
instead of Question
. This consideration is quite accepted in the community.
现在,其他需要Question
组件将使用QuestionContainer
而不是Question
。 这种考虑在社区中已经被广泛接受。
Using this setState
is pretty straightforward.
使用此setState
非常简单。
Pass the next state as the first and only parameter. It will update current state properties with the new passed values.
将下一个状态作为第一个也是唯一的参数。 它将使用新传递的值更新当前状态属性。
// Very bad pratice: do not use this.state and this.props in setState !this.setState({ answered: !this.state.answered, answer });// With quite big states: the tempatation becomes bigger // Here keep the current state and add answer propertythis.setState({ ...this.state, answer });
To sum up, don’t use this.state
and this.props
inside setState
calls.
总结起来,不要在setState
调用中使用this.state
和this.props
。
Those variables may not have the values you expect. React optimizes state changes. It squashes multiples changes into one for performance issues (before Virtual DOM optimizations).
这些变量可能没有您期望的值。 React优化状态更改。 它针对性能问题将多个更改压缩为一个(在虚拟DOM优化之前)。
// Note the () notation around the object which makes the JS engine// evaluate as an expression and not as the arrow function blockthis.setState((prevState, props) => ({ ...prevState, answer}));
You should prefer the other form of setState
. Provide a function as the only parameter and use prop
and state
parameters ().
您应该更喜欢setState
的其他形式。 提供一个函数作为唯一参数,并使用prop
和state
参数( )。
In this article, we’ve covered the main state usages in React. You can find the complete code for the Survey
component in the following Codepen.
在本文中,我们介绍了React中的主要状态用法。 您可以在以下Codepen中找到Survey
组件的完整代码。
That was all about states. You’ve encountered components, props, and states, and now you have the beginner kit to play with React.
那就是关于国家的一切。 您已经遇到了组件,道具和状态,现在您可以使用React的初学者工具包了。
I hope you enjoyed reading this article and learned a lot of things!
希望您喜欢阅读本文并学到很多东西!
If you found this article useful, please click on the ? button a few times to make others find the article and to show your support! ?
如果您发现本文有用,请单击“ ?”。 几次单击以使其他人找到该文章并表示您的支持! ?
Don’t forget to follow me to get notified of my upcoming articles ?
别忘了跟随我以获取有关我即将发表的文章的通知吗?
This is part of my “React for beginners” series on introducing React, its core features and best practices to follow.
这是我的“初学者React”系列的一部分,该系列介绍了React,其核心功能和可遵循的最佳实践。
|
|
?
?
翻译自:
react 左右互动
转载地址:http://djwzd.baihongyu.com/