【问题标题】:React Props to Pass Large Set of ObjectReact Props 传递大量对象
【发布时间】:2022-12-11 19:34:17
【问题描述】:

我有一个场景,我想首先发出请求并验证来自服务器的响应,然后显示 UI。 Complete Response 也需要在组件中传递。我有示例代码,我从服务器得到了正确的响应,但它没有传递给组件。我正在使用道具将数据传递给组件。我怎样才能做到这一点?

索引.tsx

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

应用程序.tsx

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { CarsGrid } from "./CarsGrid";


const init = async () => {
  try {
    const response = await fetch(
      "https://www.ag-grid.com/example-assets/row-data.json"
    )
    return await response.json();

  } catch (err) {}
};

function App() {
  init().then(result=> {
    console.log('Correct Response is printed',result);
    return <CarsGrid gridRows={result} />;
  });
  return (<></>)
}

export default App;

反应组件

export function CarsGrid({gridRows}) {
console.log('Data gridRows', gridRows);
})

但是结果不会打印在 console.log('Data gridRows', gridRows); 中,尽管响应打印在 console.log('Correct Response is printed',result);

任何帮助表示赞赏。

【问题讨论】:

    标签: javascript reactjs react-native react-hooks


    【解决方案1】:

    您的代码中的返回:

    init().then(result=> {
      console.log('Correct Response is printed',result);
      return <CarsGrid gridRows={result} />;
    });
    

    正在返回传递给then 的回调,而不是作为您的 App 功能/组件的渲染结果。

    所以 init().then() 部分对渲染过程没有贡献。这就好像你的应用程序代码是:

    function App() {
      return (<></>)
    }
    

    所以你的CarsGrid函数永远不会被执行。

    一种“反应”方式是依赖状态并在效果中获取数据:

    function App() {
      const [data, setData] = useState();
    
      useEffect(() => {
        const init = async () => {
          try {
            const response = await fetch(
              "https://www.ag-grid.com/example-assets/row-data.json"
            );
            const result = await response.json();
    
            console.log('Correct Response is printed',result);
    
            setData(result);
          } catch (err) {}
        };
    
        init();
      }, []);
    
      return data && <CarsGrid gridRows={data} />;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2018-04-06
      • 2023-01-09
      • 2019-08-11
      • 1970-01-01
      • 2022-10-25
      • 2023-03-08
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多