[英]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.