在功能性反应组件中获取未定义的道具
Posted
技术标签:
【中文标题】在功能性反应组件中获取未定义的道具【英文标题】:Getting undefined props in functional react components 【发布时间】:2021-10-16 06:24:14 【问题描述】:如何在执行 setRequests 后将 requests 属性传递给 RequestRow 组件?我的理解是,请求在开始时被初始化为未定义,在使用异步调用的对象进行设置之前,它以未定义的形式传递给 RequestRow 组件,并发生错误。
import React, useState, useEffect from 'react';
import 'semantic-ui-css/semantic.min.css';
import Layout from '../../../components/Layout';
import Button from 'semantic-ui-react';
import Link from '../../../routes';
import Campaign from '../../../blockchain/campaign';
import Table from 'semantic-ui-react';
import RequestRow from '../../../components/RequestRow';
const RequestsIndex = ( address ) =>
const Header, Row, HeaderCell, Body = Table;
const campaign = Campaign(address);
const [requestCount, setRequestCount] = useState();
const [requests, setRequests] = useState([]);
const getRequests = async () =>
const count = await campaign.methods.getRequestsCount().call();
setRequestCount(count);
;
let r;
const req = async () =>
r = await Promise.all(
Array(parseInt(requestCount))
.fill()
.map((_element, index) =>
return campaign.methods.requests(index).call();
)
);
setRequests(r);
;
useEffect(() =>
getRequests();
if (requestCount)
req();
, [requestCount]);
return (
<Layout>
<h3>Requests List.</h3>
<Link route=`/campaigns/$address/requests/new`>
<a>
<Button primary>Add Request</Button>
</a>
</Link>
<Table>
<Header>
<Row>
<HeaderCell>ID</HeaderCell>
<HeaderCell>Description</HeaderCell>
<HeaderCell>Amount</HeaderCell>
<HeaderCell>Recipient</HeaderCell>
<HeaderCell>Approval Count</HeaderCell>
<HeaderCell>Approve</HeaderCell>
<HeaderCell>Finalize</HeaderCell>
</Row>
</Header>
<Body>
<Row>
<RequestRow requests=requests></RequestRow>
</Row>
</Body>
</Table>
</Layout>
);
;
export async function getServerSideProps(context)
const address = context.query.address;
return
props: address ,
;
export default RequestsIndex;
RequestRow 组件如下所示。它接受 requests 属性,不幸的是它是未定义的。
const RequestRow = ( requests ) =>
return requests.map((request, index) =>
return (
<>
<div>Request!!!</div>
</>
);
);
;
export default RequestRow;
错误截图如下:
【问题讨论】:
【参考方案1】:我认为 React 试图在你的承诺解决之前渲染你的组件。如果是这种情况,您需要做的就是为您的请求设置一个默认值(在您的情况下为空数组)。
const [requests, setRequests] = useState([]);
愿原力与你同在。
【讨论】:
我做到了,但错误仍然存在。 :( 更新 - 我对 useEffect 钩子做了一些更改,它起作用了。谢谢!!以上是关于在功能性反应组件中获取未定义的道具的主要内容,如果未能解决你的问题,请参考以下文章