我是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>
);
}
}
我尝试将最后两个数字存储在状态属性中,以便我可以将它们添加到下一个序列中。但是,它似乎不起作用。我该怎么做才能做得更好?
答案 0 :(得分:1)
检查工作代码,您不需要单独的计数变量来存储系列值,previous1将始终具有该值。
如何更新系列值:
在&#39; +&#39; 期间:每一步previous1
将等于(previous1 + previous2)
而previous2
将采用{{1}价值。
在&#39; - &#39;: previous1
将成为previous1
而prevoious2
将取值previous2
< / p>
previous1 - previous2
&#13;
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'))
&#13;
注意:将条件置于减函数中,当状态变量的值为1和0时,否则将取负值。
答案 1 :(得分:0)
如果使用React钩子,事情可能会很简单。使用ref保留先前的计数,当当前计数更改时,将先前的计数和当前计数相加。就是这样。
在这里,我将先前的计数移到了usePrevious
钩中。
const App = () => {
const [count, setCount] = useState(1);
const previousCount = usePrevious(count); // hold the previous count
const addCount = () => {
setCount(count + previousCount);
};
return (
<div>
<div>previousCount: {previousCount}</div>
<div>count: {count}</div>
<button onClick={addCount}>click me</button>
</div>
);
}
usePrevious.js
:
const usePrevious = value => {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default usePrevious;