为什么我的组件没有使用 render prop 渲染?

问题描述 投票:0回答:1

我的 .js 文件中有以下数据结构:

const mylinks = [
  {
    icon: icon1,
    url: "url1",
  },
  {
    icon: icon2,
    url: "url2",
  },
  {
    icon: icon3,
    url: "url3",
  },
];

我创建了一个“链接获取器”,它应该返回在

mylinks
属性中设置的
render
对象中的图标和链接。

const LinksFetcher = ({render}) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    setData(mylinks)}, []);
  return render(data);
};

最后,我创建了一个 React 组件,它使用

render
属性来

const MyLinks = () => {
  return (
    <LinksFetcher
      render={(data) => {
        <HStack spacing={20}>
          <a href={data.url}>
            <FontAwesomeIcon icon={data.icon} size="2x"/>
          </a>
        </HStack>
      }}
    />
  );
};
<nav>
  {
    <MyLinks /> // This doesn't render
  }
</nav>

显然,当我将一些硬编码元素放入

nav
标签内时,它工作正常;让我相信我如何使用
useEffect
render
道具中设置数据。令人困惑的部分是,当我放置
console.log(mylinks)
时,我可以很好地看到结构。 为什么我无法使用此返回属性并在我的自定义组件中使用?

HStack
是从我安装的
Chakra-UI
FontAwesomeIcon
导入的组件。您的答案不需要使用其中任何一个。我需要知道的是为什么
@fortawesome/react-fontawesome
功能没有按我的预期工作。
我尝试过的事情

    useEffect
  1. 中的
    h1
    元素进行硬编码以查看它们是否渲染(它们确实渲染)
    设置 
  2. nav
  3. 以包含一个链接对象(不起作用)
  4. data
  5. 函数的第二个参数中使用扩展运算符来使用我的
    useEffect
    对象的任何先前值(不起作用)
    我用字符串数组替换了链接数组。这适用于相同的模式。这似乎表明 
  6. data
  7. 钩子可能工作正常,这是一个与我如何访问
    useEffect
    对象相关的问题。
    
        
javascript reactjs jsx
1个回答
0
投票
data

render
是如何工作的,我不太明白 @mandy8055 试图告诉我我的实现有什么问题。最终,感谢发布的评论,我解决了这个问题。
useEffect

正如我怀疑的那样,其余逻辑工作正常,因为正如我在原始问题中发布的那样,当用字符串数组替换 
const MyLinks = () => { //First, I needed to create a list of my items and create an "a" tag for each mapped item... const listData = mylinks.map((item) => { return <a href={item.url}>Link</a> // return was missing here }); //Then, I needed to return the list of items using a React fragment return( <>{listData}</> ); };

数组或对象时,它工作得很好。

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.