首页 > 解决方案 > 在 render 方法中如何默认调用函数?

问题描述

出于某种原因,它实际上并没有访问练习方法。有人可以告诉我我在这里做错了什么。欣赏它!

class StartWorkout extends Component {
  state = {
    step: 0
  };

  exercises = () => {
    const { exerciselist } = this.props.selectedWorkout;
    const { step } = this.state.step;
    while (step < exerciselist.length) {
      return <StartExercise exercise={exerciselist[step]} />;
    }
  };

  render() {
    const { name } = this.props.selectedWorkout;
    const { step } = this.state;
    return (
      <>
        <ClientMenuBar title={name} />
        <Container maxWidth="xl">
          {this.exercises()}
          <div style={styles.buttonWrapper}>
            <Button
              color="inherit"
              variant="contained"
              style={styles.button}
              size="large"
            >
              Back
            </Button>
            <Button
              color="primary"
              variant="contained"
              type="submit"
              style={styles.button}
              size="large"
              onClick={() => {
                this.setState({ step: step + 1 });
              }}
            >
              Next
            </Button>
          </div>
        </Container>
      </>
    );
  }
}

我知道它实际上并没有进入该方法,因为我在访问它之前和函数中的 while 循环之前就在控制台记录,并且它只调用第一个。

标签: javascriptreactjs

解决方案


问题在于练习方法。在这里,您尝试stepthis.state.step. 更换const { step } = this.state.step;。由const { step } = this.state;.

step请注意,您尝试访问的额外属性为 false undefinedundefined < any number因此 while 循环中的代码永远不会被执行。


推荐阅读