我正在尝试在我的render函数中渲染arr
。代码没有给出任何错误。在这里,我试图计算斐波那契数列并将其显示在屏幕上。代码是当我在文本字段中输入特定数字时,它不会在屏幕上打印序列,但是当我清除文本字段而不刷新时,它将在屏幕上打印正确的序列。我无法理解此错误的出处
import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import './App.css';
function App() {
const [limit, setLimit] = useState(1);
const [arr, setArr] = useState([]);
function handleGenerateFibonacci(event) {
for (const n of generator(limit)) {
arr.push(n)
setArr(arr)
}
event.preventDefault();
}
function* generator(limit) {
var i = 0;
var a = 0;
var b = 1;
yield a;
yield b;
for (i = 1; i <= limit - 1; i++) {
var fibNumber = a + b
yield fibNumber
a = b
b = fibNumber
}
}
return (
<div className="App">
<form >
<h1>Generating the Fibonacci Series</h1>
<h2>Enter the range</h2>
<TextField onChange={e => setLimit(e.target.value)}></TextField>
<br />
<Button onClick={handleGenerateFibonacci} type="submit" style={{
height: 40,
width: 160,
borderRadius: 10,
backgroundColor: "Blue",
marginLeft: 50,
marginRight: 50,
marginTop: 20,
fontSize: 16,
color: "white"
}} >Calculate</Button>
<br />
<h2>Result:</h2>
<div >
<p>Fibonacci Series : {"[ " + arr + " ]"}</p>
</div>
</form>
</div>
);
}
export default App;
答案 0 :(得分:2)
因为当您单击按钮时,代码本身不会更改值,而只是更改内容
let space = { 'A':{m1: 20, m2: 15, m3: 10}, 'B': {m1: 10, m2: 12, m3: 10}, 'C': {m1: 15, m2: 10, m3: 30}}
let inp = {m1: 30, m2: 17, m3: 20}
Object.keys(space).forEach(key => {
console.log(key + ' - ' + JSON.stringify(space[key])+ '- distance: ' +distance(inp, space[key]))
})
function distance(A,B){
return Math.sqrt(Math.pow(A.m1 - B.m1,2) + Math.pow(A.m2 - B.m2,2) + Math.pow(A.m3 - B.m3,2))
}
...因此系统并不真正知道您的数组已更改,因此最好以这种方式编写
function handleGenerateFibonacci(event) {
for (const n of generator(limit)) {
arr.push(n)
setArr(arr)
}
event.preventDefault();
}
当您清理文本字段时,PS,状态的limit属性正确更改,因此系统会刷新组件
答案 1 :(得分:1)
尝试这种方法,
function handleGenerateFibonacci(event) {
for (const n of generator(limit)) {
setArr((a) => [...a, n]);
}
event.preventDefault();
}
工作演示-https://codesandbox.io/s/festive-mayer-xu91t?file=/src/App.js:270-423