我们如何使用React.lazy()
和Suspense
在下面的例子中。我从FirstComponent.js
. 如何使用 FirstComponent 值添加newNumber
和显示总数。所以每次渲染时,我们应该根据接收到的随机值得到不同的总数。那可能吗 ?
https://codesandbox.io/s/condescending-lamarr-ny680?file=/src/App.js:0-635
import React, { Suspense, useState, useEffect } from "react";
import "./styles.css";
const FirstComponent = React.lazy(() => import("./other/FirstComponent"));
const SecondComponent = React.lazy(() => import("./other/SecondComponent"));
export default function App() {
const [newNumber, setNewNumber] = useState("");
useEffect(() => {
const num1 = 100;
setNewNumber(num1);
}, []);
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<FirstComponent />
{newNumber + FirstComponent}
</section>
<section>
<SecondComponent />
</section>
</Suspense>
</div>
);
}
FirstComponent.js
import React, { useState, useEffect } from "react";
const FirstComponent = () => {
const [numbers, setNumbers] = useState("");
useEffect(() => {
const randomNumber = [];
const data = [10, 20, 30, 40, 50, 60];
const random = Math.floor(Math.random() * data.length);
randomNumber.push(data[random]);
setNumbers(randomNumber);
}, []);
return <div>Hello First: {numbers}</div>;
};
export default FirstComponent;
SecondComponent.js
import React from "react";
const SecondComponent = () => {
return <div>Hello Second</div>;
};
export default SecondComponent;