大家!我面临着我的组件被渲染两次的问题。我发现这是因为同时使用useEffect和useSelector而发生的,但我不知道如何修复它。我没有使用 React.StrictMode。
import React, {useEffect, useMemo, useState} from "react";
import {useIntl} from "react-intl";
import Typography from "../../../components/Typography";
import Card from "../../../components/Card";
import CardTitle from "../../../components/CardTitle";
import {useDispatch, useSelector} from "react-redux";
import songActions from 'app/actions/song'
function List() {
const dispatch = useDispatch();
const {
formatMessage,
} = useIntl();
useEffect(() => {
dispatch(songActions.fetchSongs());
}, [])
const reduxState = useSelector((store) => store);
console.log(reduxState);
return (
<>
<Typography>
{formatMessage({ id: 'title' })}
</Typography>
{/*<div>*/}
{/* { songs.map(item => {*/}
{/* <Card>*/}
{/* <CardTitle>*/}
{/* ${item.id}*/}
{/* </CardTitle>*/}
{/* </Card>*/}
{/* })}*/}
{/*</div>*/}
</>
);
}
export default List;
我尝试在 useUpdateEffect.js 中使用 useRef,如下所示:
import { useEffect, useRef } from "react"
export default function useUpdateEffect(callback, dependencies) {
const firstRenderRef = useRef(true)
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false
return
}
return callback()
}, dependencies)
}
它不是渲染组件两次,但我的数据因此无法获取。
改变了!
好吧,我发现了双重加载错误,但随后出现了另一个错误。此代码应显示带有 redux 状态对象值的卡片。但显示的是一个空的 div。我该如何解决它?
这是组件的更新代码:
import React, {useEffect} from "react";
import {useIntl} from "react-intl";
import Typography from "../../../components/Typography";
import Card from "../../../components/Card";
import CardTitle from "../../../components/CardTitle";
import {useSelector} from "react-redux";
function List() {
const {
formatMessage,
} = useIntl();
useEffect(() => {
console.log('Hello');
}, [])
const songs = useSelector((store) => store.song.songs);
return (
<>
{}
<Typography>
{formatMessage({ id: 'title' })}
</Typography>
<div>
{songs.map(item => {
<Card>
<CardTitle>
${item.id}
</CardTitle>
</Card>
})}
</div>
</>
);
}
export default List;
您在地图功能中错过了一些东西。
你应该这样写。
{songs.map(item => (
<Card>
<CardTitle>
{item.id}
</CardTitle>
</Card>
))}