关于react usestate和setstate的嵌套问题
nested problems about react usestate and setstate
你好我模仿了一个项目没有问题但是不能显示ui,不知道是什么问题is.The对象项目link:https://codesandbox.io/s/learning-react-color-organizer-2-iytxb?file=/src/StarRating.js
我的项目link: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>
);
}
不,我的意思是从 return
块中删除 { }
大括号。
另外,更改此行:
<AiFillDelete onClick={onDelete(id)} />
为此(现在你在每次重新渲染时调用它):
<AiFillDelete onClick={() => onDelete(id)} />
你好我模仿了一个项目没有问题但是不能显示ui,不知道是什么问题is.The对象项目link:https://codesandbox.io/s/learning-react-color-organizer-2-iytxb?file=/src/StarRating.js
我的项目link: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>
);
}
不,我的意思是从 return
块中删除 { }
大括号。
另外,更改此行:
<AiFillDelete onClick={onDelete(id)} />
为此(现在你在每次重新渲染时调用它):
<AiFillDelete onClick={() => onDelete(id)} />