首页 > 解决方案 > this.setState() 似乎不能采用非立即函数

问题描述

我有一个反应类:

            class App extends React.Component{
                // Make a constructor to hold attributes in memory.
                constructor(props){
                    // This line is needed to instantiate
                    super(props)
                    // Attributes when this object is init for first time.
                    this.state = {
                        count:0
                    }
                }

                render(){
                    return (
                        <div>
                            <h1>{this.state.count}</h1>
                            <button onClick={this.count}>Count!</button>
                        </div>
                    
                    );
                }
                // Set the count attribute to point to some nameless function.
                count = () => {
                    //  a built in method to update state of an object.
                    // setState takes a state and does the following.  
                    this.setState(state => ({
                        count:state.count + 1   
                    })

                    )
                }
            }

this.setState 正确地采用了匿名函数。但是,当我尝试像这样传递一个非匿名函数时,我得到一个错误:ReferenceError: Can't find variable: state rethrowCaughtError — react-dom.development.js:321:

                count = () => {
                    //  a built in method to update state of an object.
                    // setState takes a state and does the following.  
                    function some_func(state){
                        count:state.count + 1   
                    }
                    this.setState(some_func(state))
                    
                }

为什么会这样?

标签: javascriptreactjs

解决方案


首先,您在函数中调用 plus 时传递了statein some_function,但您没有返回任何内容。试试这个:

count = () => {
    //  a built in method to update state of an object.
    // setState takes a state and does the following.
    function some_func(state){
      return {...state, count: state.count + 1}
    }
    this.setState(some_func(this.state))
  };

推荐阅读