React中的到达路由器不会在同一路径上使用urlParams重新呈现

问题描述

我正在内部UI上创建一个单页应用程序。屏幕左侧(CollectionsInventory)上出现一个菜单,其中包含通过API调用生成的Link,右侧显示的是结果对象(Collection)。他的组成部分。该道具通过url-parameters传递。我还使用patternfly4中的Grid组件来管理UI。看起来像这样:

<Grid hasGutter>
  <GridItem span={3}>
    {data != null ?
      <CollectionsInventory collections={data[0].collections}/>
    :
      <React.Fragment>
        <Spinner />
      </React.Fragment>
    }
  </GridItem>
  <GridItem span={9}>
    <Router primary={false}>
      <React.Fragment path="/" />
      <Collection path="collection/:collectionName" />
    </Router>
  </GridItem>
</Grid>

这是问题所在;我可以通过单击相应的链接或直接访问它来显示收藏集(如果用户想访问他收藏的收藏夹中的书签,则很有用)。但随后,集合被卡在那里。每当我单击新链接时,都不会改变。也许是因为它在同一条道路上?有没有一种方法可以使链接触发重新渲染?还是因为包含链接的菜单在路由器外部,所以我使用的组件不正确吗?

CollectionsInventory中,链接显示在一个表中,并根据类似这样的集合名称生成:

const defaultRows = collectionList.map( collection => {
  const collectionLink=`collection/${encodeURI(collection.name)}`

  return {
    cells: [
      {
        title:
          <Link to={collectionLink}>
            {collection.name}
          </Link>,name: collection.name
      },collection.resourceType,collection.size
    ]
  }
});

解决方法

问题在于,Collection道具更新后,我的collectionName组件没有重新渲染。我坚信无论何时更改道具,React组件都会重新渲染,但事实并非如此。因此,我在props.collectionName中添加了一个效果,以便在apiFetch进程更改时重新启动它,瞧!每当我选择新链接时,Collection组件就会更新。

奖金:确切地说,我使用的fetchApi方法是一个回调,每次修改props.collectionName时都会对其进行修改。这是简化版:

const Collection = ({ collectionName }) => {
  const fetchData = useCallback(()=>{
    const apiPath = `/collection/${collectionName}`;
    /* do stuff to retrieve the data and set it in the state,or handle errors*/
  },[collectionName]);

  useEffect(()=>{
    fetchData();
  },[fetchData]);

  return(
   /*The actual content*/
  );
};

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...