gpt4 book ai didi

javascript - React.js 中的斐波那契计数器

转载 作者:行者123 更新时间:2023-11-29 19:04:34 25 4
gpt4 key购买 nike

我是 React 的初学者。我正在尝试为斐波那契数列做一个计数器。对于那些不知道什么是斐波那契数列的人,这里有一个 guide .它在开始时起作用,然后开始偏离顺序。我希望能够显示斐波那契数列中的数字并在数列中上下移动。到目前为止,这是我的代码:

import React, { Component } from 'react';

export default class App extends Component {
constructor(props) {
super(props);

this.state = {
previous1: 1,
previous2: 1,
count: 1
}

this.clickDecrease = this.clickDecrease.bind(this);
this.clickIncrease = this.clickIncrease.bind(this);
}

clickIncrease(e) {
this.setState({
previous1: this.state.count,
previous2: this.state.previous1,
count: this.state.previous1 + this.state.previous2
});
}

clickDecrease(e) {
this.setState({
previous1: this.state.previous2,
previous2: this.state.count - this.state.previous1,
count: this.state.previous1
});
}

render() {
return (
<div>
The current number is: {this.state.count}
<button onClick={this.clickDecrease} className="btn btn-danger">-</button>
<button onClick={this.clickIncrease} className="btn btn-primary">+</button>
</div>
);
}
}

我试图将最后两个数字存储在状态的一个属性中,这样我就可以将它们相加以获得下一个序列。但是,它似乎不起作用。我应该怎么做才能让它变得更好?

最佳答案

检查工作代码,您不需要单独的计数变量来存储系列值,previous1 将始终具有该值。

如何更新系列值:

在“+”期间:在每一步 previous1 将等于 (previous1 + previous2)previous2 将采用 previous1 值。

在“-”期间: previous1 将变为 prevoious2previous2 将采用 的值previous1 - previous2

class App extends React.Component {
constructor(props) {
super(props);

this.state = {
previous1: 1,
previous2: 0,
}

this.clickDecrease = this.clickDecrease.bind(this);
this.clickIncrease = this.clickIncrease.bind(this);
}

clickIncrease(e) {
let a = this.state.previous1 + this.state.previous2;
this.setState({
previous1: a,
previous2: this.state.previous1,
});
}

clickDecrease(e) {
this.setState({
previous1: this.state.previous2,
previous2: this.state.previous1 - this.state.previous2,
});
}

render() {
return (
<div>
The current number is: {this.state.previous1}
<br/>
<button onClick={this.clickDecrease} className="btn btn-danger">-</button>
<button onClick={this.clickIncrease} className="btn btn-primary">+</button>
</div>
);
}
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id ='app'/>

注意:将条件放在reduce函数中,当state变量的值为1和0时,否则取负值。

关于javascript - React.js 中的斐波那契计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43949677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com