javascript - 在 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 循环之前就在控制台记录,并且它只调用第一个。
解决方案
问题在于练习方法。在这里,您尝试step
从this.state.step
. 更换const { step } = this.state.step;
。由const { step } = this.state;
.
step
请注意,您尝试访问的额外属性为 false undefined
,undefined < any number
因此 while 循环中的代码永远不会被执行。
推荐阅读
- jpa - @ManyToOne,其中目标 PK 是 FK 的一部分
- html - 如何使用css调整图像大小以填充行?
- c - 从文件 c 中读取
- graphql - Graphql 查询节点执行顺序
- angular - 如果在离子中,用 ng 承诺
- amazon-web-services - AWS SQS 队列 url 的格式
- android - react-native npm 模块中的第 3 方 maven 依赖项
- python - Python - 从 csv 读取数据,然后使用循环中的数据和文件号写入新的 csv
- node.js - 在网站中引入翻译后的 React 组件的最佳实践?
- c# - 如果应用程序使用任务管理器关闭,c# 表单关闭事件会起作用吗?