Issue
You are creating and sorting arrays in the component body of a functional component, which is a side-effect and anti-pattern in React.
export default function Quicksort() {
var arr = new Array(50); // <-- side-effect
for (var i = 0; i < 50; ++i) {
arr[i] = Math.floor(Math.random() * Math.floor(400)); // <-- side-effect
}
console.log(arr); // <-- side-effect
arr.sort(function (a, b) { // <-- side-effect
return a - b;
});
console.log(arr); // <-- side-effect
const mp = arr.map((num, idx) => {
return <Bar key={idx} height={num} />;
});
return (
<>
<div className="layout">{mp}</div>
</>
);
}
The entire body of a functional component IS the render function and your side-effects are being called during the "render phase" and messing with the output/returned UI in the "commit phase" when the ReactDOM is pushed to the browser DOM.
Solution
Create the array data outside the component, and thus outside the React component lifecycle, or put it in state so it is bound to the component lifecycle. Use an useEffect
hook to correctly log the array when the component renders to the DOM.
export default function Quicksort() {
const [arr] = React.useState(
[...Array(50)]
.map(() => Math.floor(Math.random() * Math.floor(400)))
.sort((a, b) => a - b)
);
React.useEffect(() => {
console.log(arr);
}, [arr]);
const mp = arr.map((num, idx) => {
return <Bar key={idx} height={num} />;
});
return (
<>
<div className="layout">{mp}</div>
</>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…