React 组件未加载 redux 状态

问题描述 投票:0回答:1

大家!我面临着我的组件被渲染两次的问题。我发现这是因为同时使用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。我该如何解决它?

Under List of entities should be cards with values

这是组件的更新代码:

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;
javascript reactjs redux react-redux
1个回答
0
投票

您在地图功能中错过了一些东西。

你应该这样写。

{songs.map(item => (
  <Card>
    <CardTitle>
      {item.id}
    </CardTitle>
  </Card>
))}
© www.soinside.com 2019 - 2024. All rights reserved.