简体   繁体   English

使用 React Hooks 的 setter,如何在组件呈现之前设置数据?

[英]With a React Hooks' setter, how can I set data before the component renders?

I export a JS object called Products to this file, just to replace a real API call initially while I am building/testing.我将一个名为 Products 的 JS object 导出到这个文件,只是为了在我构建/测试时替换一个真正的 API 调用。 I want to set the function's state to the object, but mapped.我想将函数的 state 设置为 object,但已映射。 I have the component looking like this:我的组件看起来像这样:

function App() {
  const [rooms, setRooms] = useState([]);
  const [days, setDays] = useState([]);
  const roomsMapped = products.data.map(room => ({
    id: room.id,
    title: room.title
  }))

  useEffect(() => {
    setRooms(roomsMapped);
  })

  return ( etc )

This returns the following error: Error: Maximum update depth exceeded .这将返回以下错误: Error: Maximum update depth exceeded

I feel like I'm missing something really obvious here, but am pretty new to React and Hooks.我觉得我在这里遗漏了一些非常明显的东西,但对 React 和 Hooks 来说还是很新的。 How can I set this data before the component renders?如何在组件呈现之前设置此数据?

Just declare it as initial value of rooms只需将其声明为rooms的初始值

 const Component = () =>{
     const [rooms, setRooms] = useState(products.data.map(room => ({
         id: room.id,
         title: room.title
      })))
 }

You can also use lazy initial state to avoid reprocessing the initial value on each render您还可以使用惰性初始 state以避免在每次渲染时重新处理初始值

 const Component = () =>{
     const [rooms, setRooms] = useState(() => products.data.map(room => ({
         id: room.id,
         title: room.title
      })))
 }

Change useEffect to this useEffect更改为此

useEffect(() => {
    setRooms(roomsMapped);
  },[])

With Lazy initialisation with function as a parameter of useState使用 function 作为useState的参数进行Lazy initialisation

import React, { useState } from "react";

function App() {
  const [rooms, setRooms] = useState(() => {
    // May be a long computation initialization
    const data = products.data || [];
    return data.map(({ id, title }) => ({ id, title }));
  });

  return (
    // JSX stuffs
  )
}

You can use default props for this.set initial value with empty list.您可以将默认道具用于 this.set 具有空列表的初始值。

You are getting 'Error: Maximum update depth exceeded', because your useEffect function doesn't have dependency array.您收到“错误:超出最大更新深度”,因为您的 useEffect function 没有依赖数组。 Best way to fix this is to pass empty array as the second argument to useEffect like this:解决此问题的最佳方法是将空数组作为第二个参数传递给 useEffect,如下所示:

useEffect(() => {
    setRooms(roomsMapped);
  },[]) <= pass empty array here 

this will prevent component to re render, it you want your component to re render on props change you can pass the props in the array like this:这将阻止组件重新渲染,如果您希望组件在道具更改时重新渲染,您可以像这样传递数组中的道具:

useEffect(() => {
    setRooms(roomsMapped);
  },[props.props1,props.props2])

here you can pass as many props as you want...在这里,您可以传递任意数量的道具...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在我可以设置图像的 src 之前反应组件渲染 - React component renders before I can set src of image 如何在 React 组件的渲染中持续记忆? - How can I persistently memoize across renders of a React component? 我如何在 React 经典的 `class` 组件中使用 React hooks? - How can I use React hooks in React classic `class` component? 如何重写组件的一部分以响应钩子 - How can I rewrite part of the component to react hooks 如何强制组件使用 React 中的钩子重新渲染? - How can I force a component to re-render with hooks in React? React 在我的组件实际拥有数据之前渲染它 - React renders my Component before it actually has Data 在页面呈现 react-native 钩子之前从 api 获取数据 - getting data from api before page renders react-native hooks 在 React Hooks 中破坏后如何设置 state 值? - How can i set state value after destructing in React Hooks? 如何在DOM体中渲染组件,即使某些其他组件呈现它的反应? - How can I render a component in DOM body even if some other component renders it in react? 当参数组件使用反应路由器在 ReactJS 中渲染时,如何避免不必要的 HOC 组件重新渲染 - How can I avoid unnecessary re rendering of an HOC component, when the parameter component renders in ReactJS with react router
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM