首页 > 解决方案 > 关于 react usestate 和 setstate 的嵌套问题

问题描述

您好我模仿一个项目,没有问题但无法显示ui,我不确定这是什么问题。对象项目链接:https ://codesandbox.io/s/learning-react-color-organizer -2-iytxb?file=/src/StarRating.js

我的项目链接:https ://codesandbox.io/s/nervous-flower-xv669?file=/src/App.js 我的项目有 2 个警告,第一个警告Each child in a list should have a unique "key" prop. 直接指向 app.js:

import React, { useState } from "react";
import Data from "./color-data.json";

import RatingList from "./RatingList";
export default function App() {

   const [colors,setColors]=useState(Data)
   const removeId=id=>{
      const newcolors=colors.filter(color=>color.id !== id);
      setColors(newcolors);
   }
   
  return (
    <div>
      {
        <RatingList
          colors={colors}
          onDelete={removeId}
          
        />
      }
    </div>
  );
}

第二个警告是 Cannot update a component (App ) while rendering a different component (ColorRating ).,它直接指向ColorRating.js

import React from "react";
import Star from "./Star";
import { AiFillDelete } from "react-icons/ai";
export default function ColorRating({id,
  title,
  color,
  rating,
  onDelete = (f) => f,
  
}) {

  return (
  
    <div>
      <h1>{title}</h1>
      <h1>
        <AiFillDelete onClick={onDelete(id)} />
      </h1>
      <h1 style={{ backgroundColor: color, padding: "30px" }}> </h1>
      {[...Array(5)].map((n, i) => (
        <Star key={i} selected={rating > i} />
      ))}
      <p>{rating} of 5 stars</p>
    </div>
  
  );
}

标签: reactjsuse-state

解决方案


不,我的意思是从块中删除{ }大括号。return

而且,改变这一行:

<AiFillDelete onClick={onDelete(id)} />

为此(现在您在每次重新渲染时调用它):

<AiFillDelete onClick={() => onDelete(id)} />

推荐阅读