簡體   English   中英

為什么我的 react redux 狀態不會導致重新渲染?

[英]Why is my react redux state not causing a re-render?

您好,我有一個問題,當我嘗試使用選擇器時,我的 redux 狀態不會導致重新渲染。 我對 react-redux 和 typescript 很陌生。 我一直在嘗試用谷歌搜索這個,大多數互聯網線程都說這是因為你需要創建一個新對象並返回它讓 redux 知道狀態已經改變。 我已經在做什么了。 但是我的對象沒有重新渲染,狀態已更新但不會導致重新渲染。

我究竟做錯了什么?

我的 Redux 減速器


import { Computer, GraphicsCard } from "../../interfaces";

const initialState: Computer = {
    graphicsCard: null,
}


interface SelectGraphicsCardAction {
    type: "SELECT_GRAPHICSCARD";
    payload: GraphicsCard;
}

interface UnselectGraphicsCardAction {
    type: "UNSELECT_GRAPHICSCARD";
}


export type Action = SelectGraphicsCardAction | UnselectGraphicsCardAction

export const computerReducer = (state = initialState, action: Action) => {
    switch(action.type){
        case "SELECT_GRAPHICSCARD": {
            const { payload } = action;
            console.log(state, payload)

           const newState = {
                ...state,
                graphicsCard: {
                    ...state.graphicsCard,
                    ...payload
                }
            }
            //This evaluates to false
            console.log(state === newState)

            return newState
        }
        case "UNSELECT_GRAPHICSCARD": {
            return {
                ...state,
                graphicsCard: null
            }
        }
        default:
            return state;
    }

} 

我的 Redux 商店

import { configureStore } from '@reduxjs/toolkit'
import { computerReducer } from './reducers/ComputerReducer'
// ...

 export const store = configureStore({
  reducer: {
    computer: computerReducer
  },
})

我在這里選擇/使用狀態。

function SelectedComputer() {
  const computer = useSelector((state: Computer) => state);
  const dispatch = useDispatch();
  const { graphicsCard } = computer;

  //Logging correct state
  console.log(computer)

  return (
    <div className="fixed top-10 right-4 bg-white rounded-t-lg">
      <p className="text-center font-bold border-b-1 border-b-black bg-gray-100 rounded-t-lg shadow-md">
        Selected Parts
      </p>
      <div className="flex flex-row">
        <CpuFill className="m-1" />
        {graphicsCard ? (
          //Not rendering this when updating state.
          <p>{graphicsCard.name}</p>
        ) : (
          <p>No Graphicscard selected!</p>
        )}
        <Trash className="flex justify-center"/>
      </div>

編輯:這是一個片段,我使用調度來更新狀態。

import React, { FC } from "react";
import { Button, Card } from "react-bootstrap";
import { useDispatch } from "react-redux";
import { Component, ComputerComponent } from "../interfaces";
import { Action } from "../redux/reducers/ComputerReducer";

interface ComponentCard {
  component: Component;
  buttonText: string;
  type: string;
}

interface DomainImage {
  [key: string]: string;
}

const ComponentCard: FC<ComponentCard> = ({ component, buttonText, type }) => {
  const dispatch = useDispatch();

  const imageMap: DomainImage = {
    "inet.se": "https://cdn.inet.se/gfx/ext/226/brand-assets/inet-logo2.jpg",
    "komplett.se":
      "https://cached-images.bonnier.news/gcs/di-bilder-prod/mly/fcb28d10-158c-485b-814c-b461baa0e188.jpeg",
    "webhallen.se":
      "https://static.wikia.nocookie.net/logopedia/images/6/65/Webhallen_2021.svg/revision/latest?cb=20220420201224",
  };

  return (
    <Card className="flex flex-row items-center w-50 shadow-md mt-2 mb-2">
      <div className="flex justify-center items-center mr-3">
        <img className="h-36 w-40 p-2" src={component.imgUrl} />
      </div>
      <div className="flex-1 text-left">
        <h4 className="text-base">{component.name}</h4>
        <p>
          <span>
            ArtNr: {component.articleNumber}, Manufacturer:{" "}
            {component.manufacturer}
          </span>
        </p>
        <h4 className="absolute right-36 top-10">
          <span>{component.price} :-</span>
        </h4>
      </div>
        <Button
          color=""
          className="absolute right-5 h-10 w-20"
          onClick={() => dispatch({ type, payload: component })}
        >
          {buttonText}
        </Button>
        <a href={component.url} target="_blank" className="absolute right-5 bottom-0">
          <img
            className="w-15 h-10"
            src={imageMap[component.domainName]}
            alt={component.name}
          />
        </a>
    </Card>
  );
};

值得一提的是,您在這里使用的是極其過時的(2019 年之前)風格的 Redux,最終將是您使用現代 Redux 編寫的代碼的 4 倍——尤其是與 TypeScript 結合使用時。

我強烈建議您遵循官方的 Redux 教程TypeScript 快速入門,它將向您展示您必須設置的所有其他類型(它比您現在擁有的要少得多)。

您的問題的根源可能是意外的狀態修改,這也可能發生在舊版 Redux 中的 reducer 之外 - 在現代 Redux 中,您會在進行突變時立即收到錯誤 - 節省您數小時的調試時間。 所以我真的建議你直接切換,你可能會擺脫這個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM