简体   繁体   English

我如何信任React.js中的状态

[英]How can i trust state in React.js

So in react, setState() is async, and may buffer calls to change state. 因此,在react中, setState()是异步的,并且可以缓冲更改状态的调用。 I get that. 我明白了。 And how you may use setState((state) => {}) like this with an optional callback if you depend on the state in some way for computing the new state. 以及如何使用setState((state) => {})与可选的回调一起使用,如果您以某种方式依赖状态来计算新状态,该如何使用它。

But lets say i don't want to simply update state, but just be sure of what it actually contains at a certain point in time? 但是可以说我不想简单地更新状态,而只是要确定它在特定时间点实际包含什么? Let's do an example: 让我们做一个例子:

I have a text field. 我有一个文本字段。 When someone edits that field it sets state with setState({ hasChanged: true }) . 当有人编辑该字段时,它将使用setState({ hasChanged: true })设置状态。 Very well. 很好。 On a onClick callback (somewhere else) i wanna check if text field is "changed" and save the the textual content of it before moving on. onClick回调上(在其他地方),我想检查文本字段是否已“更改”,并在继续之前保存其文本内容。 But the thing is i can never really be sure state.hasChanged actually is in sync with reality. 但问题是我永远无法真正确定state.hasChanged实际上与现实保持同步。 Unlike the callback in setState((state) => {}) , i'm on my own here. setState((state) => {})的回调不同,我在这里独自一人。

So do i create a "shadow state" (or, at least a state variable decoupled from the react state) and keep it updated just for situations such as this? 那么,我是否要创建一个“影子状态”(或者至少是一个与反应状态分离的状态变量),并仅针对诸如此类的情况进行更新? Seems a little cumbersome, and i suspect this is not how you are supposed to do it, hence this question. 似乎有点麻烦,我怀疑这不是您应该怎么做,因此是这个问题。

EDIT for clarification: i only wish to "check" state and be sure of it's content (because i'm my case, i will do a save-to-disk depending on it). 编辑以澄清问题:我只希望“检查”状态并确保其内容(因为我是我的情况,因此我将视情况对磁盘进行保存)。 I'm actually not gonna update the state. 我实际上不会更新状态。 If that was the case, setState with callback would probably be the right choice.. 如果是这种情况,则带回调的setState可能是正确的选择。

This is a fairly theoretical question and this will most likely never be a problem for scenario's like the example you gave. 这是一个相当理论上的问题,对于您所给出的示例来说,这绝不会成为问题。

Anyways, you can pass a callback to setState as a second parameter, it will get called as soon as your state has been changed. 无论如何,您可以将回调作为第二个参数传递给setState,状态更改后将立即调用它。

That's why React has a lifecycle in which you can listen via methods such as componentWillUpdate , componentDidUpdate , etc (you can check the full list here ). 这就是为什么React具有生命周期的原因,您可以在其中通过诸如componentWillUpdatecomponentDidUpdate等方法进行侦听(您可以在此处查看完整列表)。 Following your example, when a text field changes, the state value is updated, and you can "intercept" this change within the methods componentWillUpdate and componentDidUpdate like this: 按照您的示例,当文本字段更改时,状态value将更新,您可以在方法componentWillUpdatecomponentDidUpdate “拦截”此更改,如下所示:

 class Main extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this._handleOnChange = this._handleOnChange.bind(this); } componentWillUpdate(nextProps, nextState) { if(nextState.value !== this.state.value) { console.log('value will update'); } } componentDidUpdate(prevProps, prevState) { if(prevState.value !== this.state.value) { console.log('value did update', this.state.value); } } render() { return ( <form> <input type='text' autoFocus onChange={this._handleOnChange} ref='text'/> </form> ); } _handleOnChange() { this.setState({ value: this.refs.text.value }); } } ReactDOM.render(<Main />, document.getElementById("main")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="main"></div> 

You can find more info about state and lifecycles in the official docs . 您可以在官方文档中找到有关状态和生命周期的更多信息。

I really think this is a very difficult case to happen. 我真的认为这是一个非常困难的情况。 We know that setState only takes a few fractions of a second to execute, and in a real scenario, when the button is clicked, the state has already changed. 我们知道setState只需花费几分之一秒的时间来执行,并且在实际情况下,单击按钮时,状态已经改变。

In order to be able to fully trust that react is doing a good job, I can think of some ideas: 为了能够完全相信react很好,我可以想到一些想法:

  • You can disable the button when this.state.hasChanged is false. this.state.hasChanged为false时,可以禁用该按钮。 So you should always wait for the next render to check the status of hasChanged and to enable it. 因此,您应始终等待下一个render以检查hasChanged的状态并启用它。

  • Use a new key inside state that says lastAction and help of componentDidUpdate to have rules such as: state为new的内部使用新键表示lastActioncomponentDidUpdate帮助来制定规则,例如:

    if (this.state.lastAction === "myLastAction")

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

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