React-Router v4 - 将参数传递给withRouter

时间:2017-12-08 06:57:32

标签: javascript reactjs react-router

此代码可以正常工作:


public class DataRepositoryFactoryTest
{
private readonly IDataRepositoryFactory _repositoryFactory;
public DataRepositoryFactoryTest(IDataRepositoryFactory repositoryFactory)
{
    _repositoryFactory = repositoryFactory;
}
public IEnumerable<RepoAEntities> GetEntitiesFromRepoA()
{
    return _repositoryFactory.GetDataRepository<IRepositoryA>().GetEntities();
}
public IEnumerable<RepoBEntities> GetEntitiesFromRepoB()
{
    return _repositoryFactory.GetDataRepository<IRepositoryB>().GetEntities();
}
public IEnumerable<RepoCEntities> GetEntitiesFromRepoC()
{
    return _repositoryFactory.GetDataRepository<IRepositoryC>().GetEntities();
}
}

现在我尝试将数组映射到同一个组件并获得错误:


public class DataRepositoryFactoryTest
{
private readonly IDataRepositoryFactory _repositoryFactory;
public DataRepositoryFactoryTest(IDataRepositoryFactory repositoryFactory)
{
    _repositoryFactory = repositoryFactory;
}
public IEnumerable<RepoAEntities> GetEntitiesFromRepoA()
{
    return _repositoryFactory.GetDataRepository<IRepositoryA>().GetEntities();
}
public IEnumerable<RepoBEntities> GetEntitiesFromRepoB()
{
    return _repositoryFactory.GetDataRepository<IRepositoryB>().GetEntities();
}
public IEnumerable<RepoCEntities> GetEntitiesFromRepoC()
{
    return _repositoryFactory.GetDataRepository<IRepositoryC>().GetEntities();
}
}

错误文本:TypeError:无法读取属性&#39; wrappedComponentRef&#39;未定义的。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

withRouter是一个高阶组件,它返回组件类MyComponent)NOT 组件实例<MyComponent />) 。

此外,LinkButton是硬编码的;它不接受物品的道具。

然后,您需要更新到以下内容:

let LinkButton = ({ history, ...item }) => (

  <ListItem button onClick={() => history.push(item.url)}>
    <ListItemIcon>
      <ListIcon />
    </ListItemIcon>
    <ListItemText primary={item.name} />
  </ListItem>
);

LinkButton = withRouter(LinkButton);

现在,循环应该是:

navItems.map(item => <LinkButton {...item} key={item.name} />);