简体   繁体   English

为什么 output 与 React setState() 不同

[英]Why is the output different with React setState()

I don't know why我不知道为什么

  • When I use this.setState({count: count+1} Clicking multiple times will only update count once当我使用this.setState({count: count+1}点击多次只会更新一次计数
  • When I use this.setState({count: this.setState.count}) Each click updates the count当我使用this.setState({count: this.setState.count})时,每次点击都会更新计数
  • Why different?为什么不同?
       class Demo extends React.Component {
            state = {count: 0};
            render() {
                const {count} = this.state;
                return  <button onClick={() => this.setState({count: count+1})}>count</button>
            }
            shouldComponentUpdate(){
                return false;
            } 

        }
  • Environment react@16.8.4环境react@16.8.4

Because their scopes are different.因为他们的范围不同。

this.setState({count: this.setState.count+1}) actions of loading state.count number and reassignment are in same onClick event scope. this.setState({count: this.setState.count+1})加载state.count号和重新分配的操作在同一个 onClick 事件 scope 中。

But count variable in this.setState({count: count+1}) is defined in upper render() scope and onClick event only receive count as upper level variable.但是this.setState({count: count+1})中的count变量定义在 upper render() scope 和 onClick 事件中只接收count作为上层变量。 Therefore, render() function is only run once, so count in render() only initialized once(loading state.count only once);因此,render() function只运行一次,所以count in render()只初始化一次(loading state.count only once); when you click button, only onClick event scope will be executed(reassignment actions will be executed multiple times), rather than render() scope. That is why count variable in onClick event will be always 0.当你点击按钮时,只会执行 onClick 事件 scope(重新分配动作会执行多次),而不是render() scope。这就是为什么 onClick 事件中的count变量将始终为 0。

There is a simple equivalent example to your case:您的案例有一个简单的等效示例:

 state={count:0} function upperLevel() { let {count} = state; function downlevel() { state = { count: count + 1 } console.log(state); } downlevel(); downlevel(); downlevel(); } upperLevel()

If we move let {count} = state;如果我们移动let {count} = state; into downlevel() then the number will be increased.进入downlevel()则数字将增加。

 state = {count: 0} function upperLevel() { //let {count} = state; function downlevel() { let {count} = state; state = {count: count + 1 } console.log(state); } downlevel(); downlevel(); downlevel(); } upperLevel()

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

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