reactjs - 关于 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>
);
}
解决方案
不,我的意思是从块中删除{ }
大括号。return
而且,改变这一行:
<AiFillDelete onClick={onDelete(id)} />
为此(现在您在每次重新渲染时调用它):
<AiFillDelete onClick={() => onDelete(id)} />
推荐阅读
- qooxdoo - 关于 qooxdoo 的一般问题
- ios - 重用具有不同视图模型类型的 UITableView
- r - 如何“映射”或“应用”以从每一列中获得最佳测试版
- node.js - 如何在猫鼬查询中连接多个字段?
- sqlalchemy - 如何抑制极长的 sqlalchemy 错误?
- android - Android:找不到 jetifier 处理器库。无法解析配置“:classpath”的所有工件
- php - Laravel 数组元素验证
- php - 尝试上传图像时,请收到此错误 fileUpload() must be an instance of Illuminate\Http\Request
- ios - 如何为 cocoapods 项目设置模块图?
- python-3.x - 在 csv 中解析日期不适用于某些文件