【问题标题】:Can't pass data from one page to another with React-Router-DOM (useHistory, useLocation)无法使用 React-Router-DOM 将数据从一个页面传递到另一个页面(useHistory,useLocation)
【发布时间】:2022-01-07 23:52:19
【问题描述】:

我有一个路由器:

      <Switch>
        <Route exact path="/">
          <CustomPaddingContainer padding="0 0.5em 1.5em">
            <TableViewComponent columns={tableAccessors} />
          </CustomPaddingContainer>
        </Route>

        <Route path="/new-objective">
          <AddNewObjectiveComponent onSubmit={onSubmitObjective} onCancel={onCancel} />
        </Route>

        <Route path="/new-kr">
          <AddNewKrComponent onSubmit={onSubmitKR} onCancel={onCancel} />
        </Route>

        <Route path="/okr-details/:id">
          <OkrDetailsWithParams />
        </Route>
      </Switch>

并且我想在单击特定按钮时将特定组件中的特定数据传递到此路由之一。更准确地说,我有这个组件:

const AddOKRButtons: FC<AddOKRButtonsProps> = ({ parentObjectiveId }) => {
  const history = useHistory();

  const onAddOkrButtonClick = () => {
    history.push('/new-objective', { parentObjectiveId: parentObjectiveId });
  };

  const onAddKrButtonClick = () => {
    history.push('/new-kr', { parentObjectiveId: parentObjectiveId });
  };

  return (
    <OkrDetailsChildrenCardsButtonContainerCentered>
      <ButtonGroup>
        <LinkButton to="/new-objective" appearance="default" onClick={onAddOkrButtonClick}>
          Add a new sub-objective
        </LinkButton>
        <LinkButton to="/new-kr" appearance="default" onClick={onAddKrButtonClick}>
          Add a new key-result
        </LinkButton>
      </ButtonGroup>
    </OkrDetailsChildrenCardsButtonContainerCentered>
  );
};

Im trying to pass the **parentObjectiveId** which is coming from props to the /new-objective page or /new-kr page in order what button was clicked. After that Im 试图在组件中使用 useLocation 挂钩获取该数据:

export const AddNewObjectiveComponent: FC<NonNullable<AddNewOKRProps>> = props => {
  const location = useLocation();
  console.log(location);

  return(<div></div>)
}

不幸的是,我在状态键中未定义,数据可能应该是:

【问题讨论】:

  • 这个AddOKRButtons 组件在哪里渲染,parentObjectiveId 属性是否传递给它?您使用的是哪种路由器组件?您能否扩展您的代码 sn-p 以包含路由器的位置和位置?

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

尝试像这样推送历史路线

history.push({
   pathname: '/new-objective', 
   state: { parentObjectiveId: parentObjectiveId }
});

我希望它对你有用。谢谢!

【讨论】:

  • 不幸的是,这个解决方案也不起作用
  • 您是否从 react-router 或 react-router-dom 导入 useLocation 和 useHistory ?还有你为两者安装了哪个版本?
  • 是的,我有 react-router-dom(版本 5.2.0)作为依赖项。我没有 react-router 作为依赖项,因为据我所知 react-router-dom 包含 react-router 的所有功能,而且没有必要。我使用的所有钩子都是导入的。
猜你喜欢
  • 1970-01-01
  • 2020-11-20
  • 2021-12-17
  • 2022-12-14
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
相关资源
最近更新 更多