gpt4 book ai didi

javascript - 了解 React 如何/为什么/何时更新 DOM 以及如何使用它

转载 作者:行者123 更新时间:2023-11-30 08:18:49 25 4
gpt4 key购买 nike

我正在制作一个应用程序,其中有 3 个按钮,其中 2 个按钮对我的问题很重要。一个按钮应向用户正在查看的网站添加元素,另一个按钮应删除元素。

我是 React 的新手,感觉自己掌握了基础知识,但显然需要更好地理解它。

我的第一直觉是创建一个数组,我可以将元素放入其中,然后将该数组作为我的一个 JSX.Elements 的内容。

看起来像这样:

我的 JSX.Element:

   answerView = (
<div>
<button onClick={this.removeIceCream}>Poista jäätelö!</button>
<button onClick={this.addIceCream}>Lisää jäätelö!</button>
<button onClick={this.keyInput}>OK</button>
<div>{this.iceCreamCount}</div>
</div>
);

向元素添加内容的函数。

addIceCream() {
this.iceCreamCount.push(<li>"Jäätelö"</li>);
}

然而,这最终会更新数组 iceCreamCount,但不会显示在 DOM 中。 React 不会对元素的变化以及仅对其状态或属性的变化做出“ react ”吗?

这是否意味着为了根据用户输入操作 DOM 元素,我包含元素的数组也需要是状态变量?


如果以上确实不可能,那么我希望获得有关如何在 React 中正确执行它的帮助,下面是我尝试这样做的尝试。

我检查了一些教程和示例并想出了这样的东西:

  addIceCream = () => {
this.setState(state => {
const iceCreams = state.iceCreams.concat(state.iceCream);

return {
iceCreams,
iceCream: 'Jäätelö',
};
});
};

我的状态声明如下所示:

this.state = { doorView: true, bunnyView: false, answerView: false, iceCream: "Jäätelö", iceCreams: [] };

在写这个问题的过程中,我实际上得到了这个看似有效的方法,但我也想了解它是如何以及为什么有效的,因为我对我的知识并不十分自信。

但是我觉得我没有掌握这里到底发生了什么。我对箭头函数不太有信心(如果有人有关于它们的简单教程,请链接)虽然我想我已经收集到了,因为 React 中的数据应该是不可变的,这就是我需要使用的原因concat() 创建一个新数组,它是旧数组的副本 + 我添加的元素。但是,为什么我需要 return() 状态变量,为什么会有这么多箭头函数被抛出(见下文我的浓缩“我想知道的列表”)?


我想知道什么

  • 我的问题的第一部分在 React 中是可行的方法还是完全错误的方法?如果可以做到,我将不胜感激,如果有人能告诉我我的想法是如何以及我的错误是什么。
  • 我的问题的第二部分为什么以及如何起作用?如果有人有时间和耐心从以下开始逐行浏览它:addIceCream = () => {.... 并告诉我发生了什么,这对我的理解和学习有很大帮助。

最佳答案

我会在下面回答问题。


第一个问题的答案

Is the first part of my question a workable way in React or is it simply the wrong approach completely? If it can be done, I would appreciate if someone would show me how and what are my mistakes in my thinking.

不幸的是,第一种方法是“完全错误的方法”(在 React 世界中)。

addIceCream() {
this.iceCreamCount.push(<li>"Jäätelö"</li>);
}

However this ends up in the array iceCreamCount updating but not being displayed in the DOM. Does React not ehmm "react" to changes in elements and only changes in its State or Properties?

就是这样。 React 对 React 跟踪的 state 和 props 变化做出“ react ”

Does this mean that in order to manipulate the DOM elements in accordance to user input my array containing the elements also needs to be a state variable?

这取决于。一些控件是“controlled”和另一个“uncontrolled”(主要适用于表单域。)

大多数时候,您会使用(React)“受控”选项来保持与 React 关联的所有状态以进行跟踪。 (在类组件中 this.state ={...} 或在使用钩子(Hook)的函数组件中,const [state, setState] = React.useState(...) )

React 的 Reconciliation (一种奇特的说法,知道发生了什么变化以及要呈现什么)算法通过检查已更改的状态/ Prop “引用”(而不是值)来工作。

当你做了 this.iceCreamCount.push(<li>"Jäätelö"</li>) ,您基本上是在更改数组“this.iceCreamCount”的值,而不是其引用。

并且在重新分配 this.iceCreamCount 之后到一个新对象,你还需要this.setState({iceCreamCount: newIceCreamCount})通知 React 某些内容已更改并需要重新渲染。

现在我们知道了为什么第一种方法不起作用,让我们继续讨论您的解决方法。


第二个问题的答案

Why and how does the second part of my question work? If someone had the time and patience to go through it line by line starting from: addIceCream = () => {.... and tell me what is happening that would help me a lot in understanding and learning.

state declaration

this.state = {
doorView: true,
bunnyView: false,
answerView: false,
iceCream: "Jäätelö",
iceCreams: []
};
addIceCream = () => {
this.setState(state => {
const iceCreams = state.iceCreams.concat(state.iceCream);

return { iceCreams, iceCream: "Jäätelö" }
};
});
};

当您查看 addIceCream 时,你确实在创建一个新的引用,iceCreams .
正如上面问题 #1 中所解释的,这就是 React 的协调算法知道状态已经改变的方式。
要点是 React 被优化以检查引用更改,因为深度属性检查(假设 this.state 具有深层嵌套对象,然后比较每个值将花费太长时间)

最后您将返回一个新的引用 return { iceCreams, iceCream: "Jäätelö" } ,它通知 React 确实发生了一些变化。


跟进评论。

how do the arrow functions here work and why they are required for the "addIceCream"-function to work?

您已声明 addIceCream使用 Arrow Functions语法。
如以下部分所述,No Separate this , 箭头函数不会创建自己的 this变量。

但是当你这样做时,this设置为父上下文的 this由于范围规则的魔力。

addIceCream = () => {
this.setState(state => {
const iceCreams = state.iceCreams.concat(state.iceCream);

return { iceCreams, iceCream: "Jäätelö" }
};
});
};

这就是为什么您可以调用 this.setState 的原因多于。 JavaScript 引擎将尝试找到最近的父项的 this在作用域链中。

如果你声明了 addIceCream作为常规方法,

class App extends React.Component {
addIceCream() { ...}
}

然后 this指向 addIceCream因此,将无法访问 Appthis.setState ,可从 React.Component 获得当你扩展它时。

因此您会看到 bind 的解决方法通过传递自己的类方法 this给它,用当前类的 this 创建一个新函数.

class App extends React.Component {
constructor(props) {
super(props)

// ...👇 this create a new method with `App`'s `this`.
this.addIceCream = this.addIceCream.bind(this)
}

addIceCream() {
// now that `this` is bound to `App`'s `this`, you can call this
this.setState({...})
}
}

这在您使用类组件 (CC) 时适用。当您使用功能组件 (FC) 时,这无关紧要。

您可以使用 React 的新 Hooks(useStateuseReducer)来保存状态。

(使用 useReducer 进行复杂的状态管理)

cosnt initialState = {
doorView: true,
bunnyView: false,
answerView: false,
iceCream: "Jäätelö",
iceCreams: []
};

function reducer(state, action) {
switch (action.type) {
case 'ADD_ICECREAM':
const { iceCream } = action.payload
const iceCreams= [...state.iceCreams].concat(iceCream)
return { ...state, iceCream, iceCreams }
default: return state;
}
}

function App() {
const [icecreams, setIceCreams] = React.reducer(reducer, initialState);
// You can use either one now.
const addIceCream = iceCream =>
dispatch({type: 'ADD_ICECREAM', payload: { iceCream }});
// OR
function addIceCream(iceCream) {
dispatch({type: 'ADD_ICECREAM', payload: { iceCream }});
}
}

reducer函数返回一个新的对象引用,因此将导致 React 重新渲染。

您可能已经注意到箭头语法版本使用 const喜欢const addIceCream = iceCream => ... .

现在它变成了一个指向函数的指针,所以它应该在使用前声明,不像 function版本因何JavaScript hoisting有效。

关于javascript - 了解 React 如何/为什么/何时更新 DOM 以及如何使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57327098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com