我在react中使用材料ui选项卡面板。我想将容器创建的组件传递到选项卡面板的组件属性。但我被无限渲染所困扰。。。我在找原因。在查看别人的代码时,我发现与我的代码不同的部分得到了回报。我想知道有什么不同。
//SupportCenterContainer.js
function RequestNotice(props) {
return <Containers.SupportNoticeListContainer />;
}
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}
在第一个函数中,您将返回组件本身,这是您期望从函数中返回的正常行为。
在第二种情况下,您将返回一个匿名函数,该函数在被调用时将返回组件本身。之所以会发生这种情况,是因为当您使用箭头函数并在箭头之后立即键入内容时,这些值将是该函数的返回值。
在第三种情况下,您使用了与箭头表示法相同的匿名函数思想,但由于值之前有一个大括号,因此必须指定该函数将返回的内容。
出于好奇,在ES6中doJS引入了箭头函数。
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
上面的代码返回一个函数,该函数将返回一个React组件。
要使用这个,你可以做
let Component = RequestNotice2(props)() // <Containers.SupportNoticeListContainer />
// render the component
<Component/>
简而言之,在ES6中,() => value
表示返回value
。但是,如果在括号后打开{
,则必须使用return value
(例如() => { return value }
(返回该值。
后者的用例是当您必须执行一些逻辑来导出值时:
() => { value = 5+8; return value }
因此,上面的每一条评论都解释了每一种情况:
// Returns the <Containers.SupportNoticeListContainer /> component
function RequestNotice(props) {
return <Containers.SupportNoticeListContainer />;
}
// Returns a function that will return <Containers.SupportNoticeListContainer /> when called
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
// same as above, will return <Containers.SupportNoticeListContainer /> when called
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}