我有一個使用 React、React Router Dom(RRD)、Redux 和 Typescript 的專案。默認情況下,RRD 將match和history道具傳遞給我在 Route 組件道具中定義的子組件(見下文)。在我的組件 Redux 中還向我的組件添加了兩個道具,一個函式(getPlaylist)和一個物件(auth)。
在我的組件中,當我輸入所有道具時,我無法輸入match和history。
我試過以下沒有運氣:
- 添加了我的自定義道具的 RouteComponentProps
History從 RRD匯入,如下所示: 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)
uj5u.com熱心網友回復:
type Props = RouteComponentProps & {
getPlaylist: Function,
playlist: Playlist,
auth: Auth,
}
像這樣?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343877.html
標籤:javascript 反应 打字稿 反应路由器 反应打字稿
