我正在尝试调用switch_func函数。但是以某种方式无法获得预期的结果

问题描述 投票:0回答:2

<!DOCTYPE html>
<html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<body>
  
<div id="root"></div>

<script type="text/babel">
class Hello extends React.Component {
  constructor(props) {
        super(props);
        this.state = { myStr: "Initial state" };
        this.switch_func = this.switch_func.bind(this);
    }
    
    switch_func = () => {
  // the setState if commented ...the initial state of myStr is executed ..meaning the function is called however the setState method doesnt work . Can anyone tell why this is happening?
  
    	this.setState({ myStr: "yess"});
      return (
            <div>
                <h3>{this.state.myStr}</h3>
            </div>
        );
    }
    

    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
				{this.switch_func()}
            </div>
        );
    }
}

ReactDOM.render(<Hello />, document.getElementById('root'))
</script>

</body>
</html>

即使绑定了功能switch_func之后,它也不会执行,并且myStr的状态仍与初始化时相同。请帮助编码无法显示所需结果的地方。

谁能说出setState方法为什么在这里不起作用?

所需的输出是myStr的状态更改为-“是,是四个!”

class MyClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {myStr: "Initial state"};
        this.switch_func = this.switch_func.bind(this);
    }
    switch_func = ()=> {
        this.setState({myStr: "In function"});
        switch (1 + 3) {
            case 2 + 2:
                this.setState({ myStr: "Yes its four!"});
                break;
            default:
                this.setState({ myStr: "Oops! default"});
        }

    return(
        <div>
            <h3>{this.state.myStr}</h3>
        </div>
    );
  }

    render(){
        return (
            <div>
            <h1>Hello, world!</h1>
            {this.switch_func()}
        </div>
        );
    }
}

ReactDOM.render(
    <MyClass />,
    document.getElementById('root')
);


javascript reactjs function-call
2个回答
0
投票

您只需要在最后加上括号即可调用该函数。这将导致无限循环,但是每次您的组件渲染时,它都会更新状态,进而导致重新渲染,等等。

class MyClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = { myStr: "Initial state" };
        this.switch_func = this.switch_func.bind(this);
    }
    switch_func = () => {
        switch (1 + 3) {
            case 2 + 2:
                this.setState({ myStr: "Yes its four!" });
                break;
            default:
                this.setState({ myStr: "Oops! default" });
        }

        return (
            <div>
                <h3>{this.state.myStr}</h3>
            </div>
        );
    }

    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                {this.switch_func()}
            </div>
        );
    }
}

ReactDOM.render(
    <MyClass />,
    document.getElementById('root')
);

0
投票

[您不应该在render内部调用switch函数,因为它可能导致您的组件陷入无限循环-每次渲染时,状态都会发生变化,因此...它会再次渲染。

而且,在一个函数中混合使用渲染和状态更新是非常危险的-永远不应该这样做,因为这可能会导致大量优化泄漏。

将函数调用移至其他方法,例如componentDidMount()

class MyClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {myStr: "Initial state"};
    }

    componentDidMount() {
      switchFunc();
    }

    switchFunc = () => {
        switch (1 + 3) {
            case 2 + 2:
                this.setState({ myStr: "Yes its four!"});
                break;
            default:
                this.setState({ myStr: "Oops! default"});
        }
    }

    render(){
        return (
            <div>
                <h1>Hello, world!</h1>
                <div>
                    <h3>{this.state.myStr}</h3>
                </div>
            </div>
        );
    }
}

ReactDOM.render(
  <MyClass />,
  document.getElementById('root')
);

componentDidMount是React提供的一种特殊方法(与render相同),可在安装组件时控制组件的行为。有关此方法的更多信息,请访问:https://reactjs.org/docs/state-and-lifecycle.html

[另外,请注意,暂时将渲染myStr与render方法分开是过大的杀伤力-就像我的示例一样,直接在render方法中直接使用它即可。]

仅作说明-尝试为您的方法使用camelCased名称,以使其与其余代码保持一致(如我的更新示例)。>>

关于绑定的另一种优化信息-您向构造函数添加了.bind()调用-不需要,因为在类之外的任何上下文中都不会使用switchFunc(因此,其this始终指向该类,因此您无需再次.bind()上下文)。另外,更重要的是-您将其编写为lambda(() => {})函数,而不是常规函数-lambda没有它们的上下文,并且从定义它们的位置继承父上下文-因此它将始终指向类this上下文,没有任何显式绑定

© www.soinside.com 2019 - 2024. All rights reserved.