在带有 useEffect 钩子的响应功能组件中未使用 .map() 显示的元素



我正在useEffect回调中创建一组类别,当我控制台时它工作正常.log它。

但是当我 .map(( 它时,生成的数组是空的。

import React, { useEffect } from 'react';
export const Categories = (props) => {
let categories = [];
useEffect(() => {
props.films.forEach((film) => {
if (categories.findIndex(item => item === film.category) === -1)
{
categories.push(film.category);
console.log(categories);
}
})
}, [props.films, categories])
return (
<div>
{categories.map((category) => {
return (
<div>
{category}
</div>
)
})}
</div>
);
}

有人有想法吗?

您应该对类别使用状态值:

const [categories, setCategories] = React.useState([])
useEffect(() => {
let categories = []
props.films.forEach((film) => {
if (categories.findIndex(item => item === film.category) === -1)
{
categories.push(film.category);
console.log(categories);
}
})
setCategories(categories)
}, [props.films])

categories中的数据发生更改时,组件不会重新呈现。为了呈现categories您需要使用useState存储数据。

import React, { useEffect, useState } from 'react';
export const Categories = (props) => {
const [categories, setCategories] = useState([]);
useEffect(() => {
let filmCategories = []
props.films.forEach((film) => {
if (categories.findIndex(item => item === film.category) === -1)
{
filmCategories.push(film.category);
console.log(filmCategories);
}
})
setCategories(filmCategories)
}, [props.films])
return (
<div>
{categories.map((category) => {
return (
<div>
{category}
</div>
)
})}
</div>
);
}

希望这有帮助。

我想你可能是新手。我建议你看看 React 状态和生命周期

您正在使用 react 钩子useEfect它将在组件在 DOM 中渲染后调用

我可以想到两种可能的解决方案来解决这个问题

1( 使用 React 钩子useState

import React, { useEffect } from 'react';
export const Categories = (props) => {
//Make the local variable into a variable representing state
let [categories, setCategories] = useState([]);
useEffect(() => {
const result = [...categories];
props.films.forEach((film) => {
if (result.findIndex(item => item === film.category) === -1)
{
result.push(film.category);
console.log(result);
}
})
//Set the state value to trigger a re-render of your component
if(result.length !== categories.length)
setCategories(result);
}, [props.films, categories])
return (
<div>
{categories.map((category) => {
return (
<div>
{category}
</div>
)
})}
</div>
);
}

2( 如果不需要重新渲染,请删除useEffect

import React, { useEffect } from 'react';
export const Categories = (props) => {
let categories = props.films.map(film => {
if (categories.findIndex(item => item === film.category) === -1)
{
categories.push(film.category);
console.log(categories);
}
}

return (
<div>
{categories.map((category) => {
return (
<div>
{category}
</div>
)
})}
</div>
);
}

如果需要 useEffect react 钩子,那么解决方案 1 更好

如果不需要重新渲染 react 组件,那么解决方案 2 更好

相关内容

  • 没有找到相关文章

最新更新