gpt4 book ai didi

reactjs - React Typescript - 在路由中传递时如何将类型添加到 location.state

转载 作者:行者123 更新时间:2023-12-03 18:31:28 25 4
gpt4 key购买 nike

当我将 react-router props 传递给路由中的组件时出现错误,因为我有特定的状态,我传递了这个组件,但错误显示在我的路由中。

enter image description here

这是路由代码:

<Route
exact
path='/flipltimeline'
render={props => <FliplTimeline {...props} />

在另一个组件中,我在下面称之为
props.history.push(`/flipltimeline`, {
Approval: singleFliplApprovals,
InvestigationID,
Unit: unit,
Cost: cost
});

这是组件的代码。我终于得到了 Typescript 来编译它,但我必须合并 LocationState 和 TimelineState 才能让它工作。但是现在当我将 Prop 发送到我的 FliplTimeline 组件时,Typescript 会抛出上面的屏幕截图。任何人都知道如何解决这个问题?

历史.tsx
import { createBrowserHistory } from 'history';

let baseNameProd = '';

if (process.env.NODE_ENV !== 'production') {
  console.log('Looks like we are in development mode!');
  baseNameProd = '';
} else {
  baseNameProd = '/flipl';
}

const customHistory = createBrowserHistory({
  basename: baseNameProd
});

export default customHistory;

翻转时间线.tsx
import * as React from 'react';
import { History, LocationState } from 'history';

interface FliplTimelineLocationState {
Approval: any;
InvestigationID: number;
Unit: string;
Cost: number;
}

interface TimelineState{
state: FliplTimelineLocationState;
}

interface Props {
history: History;
location: LocationState & TimelineState;
}

function FliplTimeline(props: Props) {
return (
<ModuleTemplate title='Status Timeline' subtitle=''>
<FliplTimelineJumbotron className='bg-primary-darker shadow-4 line-height-serif-4'>
<div className='grid-row'>
<div className='grid-col-4'>
<span
className='font-mono-2xl text-white'
style={{
verticalAlign: 'middle'
}}
>
FLIPL{' '}
</span>
<span
className='font-mono-xl text-gold'
style={{
verticalAlign: 'middle'
}}
>
{props.location.state.InvestigationID}
</span>

更新:添加了我的 history.tsx 文件,我在其中为 React-Router 创建了自己的历史记录。还添加在导入语句中。

更新:尝试将我的 FliplTimeline 组件更改为具有此界面
import { RouteComponentProps } from 'react-router-dom'

function FliplTimeline(props: RouteComponentProps ) {

我收到 2 个错误。第一个是这个,另一个说 Prop 的形状是错误的。想法?
tserror

更新:我终于能够为我的组件获得正确的 props 声明。
import { RouteComponentProps } from 'react-router-dom';

interface FliplTimelineLocationState {
Approval: any;
InvestigationID: number;
Unit: string;
Cost: number;
}

function FliplTimeline(
props: RouteComponentProps<{}, any, FliplTimelineLocationState | any>
)

最佳答案

我能够让它工作。

import { RouteComponentProps } from 'react-router-dom';

interface FliplTimelineLocationState {
Approval: any;
InvestigationID: number;
Unit: string;
Cost: number;
}

function FliplTimeline(
props: RouteComponentProps<{}, any, FliplTimelineLocationState | any>
)

关于reactjs - React Typescript - 在路由中传递时如何将类型添加到 location.state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com