Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

reactjs - nested problems about react usestate and setstate

Hi I mimic a project and there is no problem but can not display the ui,I am not sure what kind of problem it is.The object project link:https://codesandbox.io/s/learning-react-color-organizer-2-iytxb?file=/src/StarRating.js

My project link:https://codesandbox.io/s/nervous-flower-xv669?file=/src/App.js My project has 2 warnings,this first warning is Each child in a list should have a unique "key" prop. which direct to the 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>
  );
}

the second warning is Cannot update a component (App) while rendering a different component (ColorRating).which direct to the 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>
  
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, I mean remove the { } curly brackets from the return block.

And also, change this line:

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

to this (right now you invoke it's on every rerender):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...