React渲染数组.地图数据两次



我有一小段react代码,它呈现了姓名列表及其相关信息,如年龄和电子邮件地址。代码编译得很好,但我看到数据在页面上呈现了两次。下面是我调用组件的方式:

const peopleData : Person[] = [{id:1,name:"John",age:22},{id:2,name:"Sasha",age:23}]
function App() {
return (
<div className="App">
<Basic {...peopleData}/>
</div>
);
}

这里是组件:

export interface Person {
id      : number;
name    : string;
age     : number;
email?  : string;
}

function Basic(input: Person[]) {
let newPeopleData : Person[] = [];
const [data,setData] = useState<Person[]>([]);
useEffect(()=>{
// Create a new data array 
let data : Person[] = Object.values(input);
let size : number = Object.values(input).length;
console.log("Data load start." + JSON.stringify(data));
for(let index=0;index<size;index++)
{
let {id,name,email} = input[index] as Person;
let newEmail = name + "@gmail.com"
newPeopleData.push({id:id,name:name,email:newEmail} as Person)
}
setData(newPeopleData);
console.log("Data loaded." + JSON.stringify(data));
return ()=>{
console.log("Data deleted." + JSON.stringify(data));
}
},[]);

return (
<div>
{data.map((unit)=>{
return (
<h1 key={unit.id}>{unit.name},age:{unit.age},email:{unit.email}</h1>
)
})}
</div>
)
}

我有两个问题:

  1. 是"peopledata"数组是否正确传递给组件?或者有没有更好的推荐方法?
  2. 为什么浏览器在刷新数据时要呈现两次,尽管"unit.id">

感谢我试图删除h1标签中的key属性,认为React可以为每个映射对象分配自己的唯一id。但这也行不通。

将数组变量移动到useEffect

useEffect(() => {
// move the variable inside as useEffect runs twice in dev strict mode
// to render it once
// The main issue: the useEffect needs to be passed 
// dependency array useEffect(() => {}, [input])
// rendering twice in dev mode helps to catch cleanup errors
let newPeopleData : Person[] = [];
// Create a new data array 
let data : Person[] = Object.values(input);
let size : number = Object.values(input).length;
console.log("Data load start." + JSON.stringify(data));
for(let index=0;index<size;index++)
{
let {id,name,email} = input[index] as Person;
let newEmail = name + "@gmail.com"
newPeopleData.push({id:id,name:name,email:newEmail} as Person)
}
setData(newPeopleData);
console.log("Data loaded." + JSON.stringify(data));
return ()=>{
console.log("Data deleted." + JSON.stringify(data));
}
},[]); // pass dependency
  1. React使用props,正确this:
<Basic data={peopleData}/>

组件中的:

interface Props {
data: Person[]
}
function Basic({data}: Props) {}
  1. 在控制台数据中渲染两次,因为索引中的react使用严格模式
<React.StrictMode>

相关内容

  • 没有找到相关文章

最新更新