[英]Can not set state with props in react
I'm trying to map over an array that I get from parent component but the problem is that even though I assign the data to state, on the initial load state is empty and that results me having an empty array.我正在尝试通过从父组件获得的数组对 map 进行处理,但问题是,即使我将数据分配给 state,在初始加载时 state 也是空的,结果我的数组为空。 I need this array in the state because I will be implementing a sorting functionality into my project and I would like to change
userData
whenever user clicks on corresponding cell.我需要 state 中的这个数组,因为我将在我的项目中实现排序功能,并且我想在用户单击相应单元格时更改
userData
。 Here is the code I have:这是我的代码:
import React, { useState } from 'react';
import { Table } from 'semantic-ui-react';
import Moment from 'react-moment';
const UserTable = ({ repoData }) => {
const [userData, setUserData] = useState(repoData);
console.log(repoData)
const descending = [].concat(repoData)
.sort((a, b) => a.name < b.name ? 1 : -1);
const ascending = [].concat(repoData)
.sort((a, b) => a.name > b.name ? 1 : -1);
function clickHandler() {
setUserData(descending)
}
return (
<div>
<Table sortable celled fixed>
<Table.Header>
<Table.Row>
<Table.HeaderCell
onClick={clickHandler}
>
Repository Name
</Table.HeaderCell>
<Table.HeaderCell
>
Description
</Table.HeaderCell>
<Table.HeaderCell
>
Created At
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{userData.map(repos => {
return <Table.Row>
<Table.Cell>{repos.name}</Table.Cell>
<Table.Cell>{repos.description}</Table.Cell>
<Table.Cell> <Moment format="DD-MM-YYYY">{repos.created_at}</Moment></Table.Cell>
</Table.Row>
})}
</Table.Body>
</Table>
</div>
);
}
export default UserTable;
Since the first logs are empty this means that the parent component passes an empty array to UserTable
.由于第一个日志是空的,这意味着父组件将一个空数组传递给
UserTable
。
If you dont want UserTable
to show when repoData
is still empty, you can do that at the parent level by checking that repoData
is defined and has a length > 0.如果您不希望
UserTable
在repoData
仍然为空时显示,您可以在父级别通过检查repoData
是否已定义并且长度 > 0 来执行此操作。
const App = () => {
...
return (
<>
...
{repoData && repoData.length ? <UserTable repoData={repoData} /> : null (or something else)}
...
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.