[英]how to define history and match type(from React Router Dom) in React/Typescript
我有一個使用 React、React Router Dom(RRD)、Redux 和 Typescript 的項目。 默認情況下,RRD 將match
和history
道具傳遞給我在 Route 組件道具中定義的子組件(見下文)。 在我的組件 Redux 中還向我的組件添加了兩個道具,一個函數(getPlaylist)和一個對象(auth)。
在我的組件中,當我輸入所有道具時,我無法輸入match
和history
。
我試過以下沒有運氣:
History
,如下所示: import { History } from "react-router-dom" 並將其用作類型(請參閱我的代碼)我的組件
import React, { useEffect, useState, useMemo, useLayoutEffect } from "react"
import { connect } from "react-redux"
import PropTypes from "prop-types"
import CreatePlaylist from "../components/playlist/CreatePlaylist"
import { getPlaylist } from "../actions/playlistActions"
import isEmpty from "../utils/isEmpty"
import { Auth, Playlist } from "interfaces"
import { RouteComponentProps } from "react-router"
import { History } from "react-router-dom"
type EditPlaystProps2 = {
getPlaylist: Function
playlist: Playlist
auth: Auth
}
interface EditPlaystProps {
history: History
auth: Auth
getPlaylist: Function
playlist: Playlist
match: any
}
function EditPlaylist({
history,
auth,
getPlaylist,
playlist,
match,
}: RouteComponentProps<EditPlaystProps2>) {
const [currentPlaylist, setcurrentPlaylist] = useState({})
useEffect(() => {
const { isAuthenticated } = auth
if (!isAuthenticated) {
history.push("/login")
}
}, [auth, history])
useLayoutEffect(() => {
getPlaylist(match.params.slug)
}, [getPlaylist, match.params.slug])
useMemo(() => {
const { isAuthenticated } = auth
if (!isAuthenticated) {
history.push("/login")
}
if (playlist) {
setcurrentPlaylist(playlist)
}
}, [auth, history, setcurrentPlaylist, playlist])
const editQupplistContent = () => {
const playlistsHaveLoaded = !isEmpty(currentPlaylist.playlist)
if (playlistsHaveLoaded) {
return (
<CreatePlaylist
name={currentPlaylist.playlist.name}
slug={currentPlaylist.playlist.slug}
id={currentPlaylist.playlist._id}
title="Edit playlist"
buttonText="Edit playlist"
/>
)
}
}
return (
<div>
<h1>Edit playlist</h1>
{editQupplistContent()}
</div>
)
}
EditPlaylist.propTypes = {
getPlaylist: PropTypes.func.isRequired,
playlist: PropTypes.object,
auth: PropTypes.object.isRequired,
}
const mapStateToProps = (state) => ({
auth: state.auth,
playlist: state.playlist,
})
export default connect(mapStateToProps, { getPlaylist })(EditPlaylist)
type Props = RouteComponentProps & {
getPlaylist: Function,
playlist: Playlist,
auth: Auth,
}
像這樣?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.