反应路由器中 location.state 的类型或接口 [英] Type or interface for location.state in react-router

查看:263
本文介绍了反应路由器中 location.state 的类型或接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个组件中,有一个 (来自 react-router-dom)在 state 属性中传递一个对象.

另一个名为 ReceiverComponent 的组件正在正确接收该对象.但是,下面的代码抱怨消息:

<块引用>

类型PoorMansUnknown"不可分配给类型locationStateProps".类型未定义"不可分配给类型'locationStateProps'.ts(2322)

type locationStateProps = {名称:字符串;}函数接收器组件(){const location = useLocation();const myState: locationStateProps = location.state;返回 (<div>{myState.name}

);}

我需要以某种方式为状态提供一种类型,而不会出现此错误.如何进行?

解决方案

有一个线程 在 Github 上公开讨论这个问题.

我实现了线程中提到的这个解决方案并且它奏效了.

interface Props 扩展 RouteComponentProps<{ myParamProp?: string },//props.match.params.myParamProp任何,//历史{ myStateProp?: string },//props.location.state.myStateProp>{myNormalProp:布尔值;}

In one component, there is a <Link> (from react-router-dom) passing an object in the state property.

Another component called ReceiverComponent is receiving that object correctly. However, the code belows complains with the message:

Type 'PoorMansUnknown' is not assignable to type 'locationStateProps'. Type 'undefined' is not assignable to type 'locationStateProps'.ts(2322)

type locationStateProps = {
  name: string;
}

function ReceiverComponent() {
  const location = useLocation();
  const myState: locationStateProps = location.state;
  return (
    <div>
      {myState.name}
    </div>
  );
}

I need to provide a type for the state some way without this error. How to proceed?

解决方案

There is a thread open on Github about this issue.

I implemented this solution mentioned on the thread and it worked.

interface Props extends RouteComponentProps<
  { myParamProp?: string }, // props.match.params.myParamProp
  any, // history
  { myStateProp?: string }, // props.location.state.myStateProp
> {
  myNormalProp: boolean;
}

这篇关于反应路由器中 location.state 的类型或接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆