0

我们如何使用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;
4

1 回答 1

1

你需要传递一个回调,因为React 中的数据会向下流动

const FirstComponent = React.lazy(() => import("./other/FirstComponent"));

export default function App() {
  const [newNumber, setNewNumber] = useState(0);
  const [randomNumber, setRandomNumber] = useState(0);

  useEffect(() => {
    setNewNumber(100);
  }, []);

  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <FirstComponent set={setRandomNumber} />
        {newNumber + randomNumber}
      </Suspense>
    </div>
  );
}

const FirstComponent = ({ set }) => {
  const [number, setNumber] = useState(0);

  useEffect(() => {
    const randomNumber = data[random];
    setNumber(randomNumber);
    set(randomNumber);
  }, [set]);

  return <div>Random Number: {number}</div>;
};

编辑 gracious-dust-1s62g

于 2020-07-16T11:39:17.750 回答