【问题标题】:Property 'original_title' does not exist on type 'string' > TypeScript类型“字符串”> TypeScript 上不存在属性“original_title”
【发布时间】:2021-12-18 17:34:37
【问题描述】:

所以,我正在使用 typescript 和 redux 创建一个网站,我正在从 TMDB(电影数据库)中提取一个 API,我已经设置了我的 redux 并且我得到了商店,在使用 use selector 和 useDispatch 之后我应该能够映射通过数组,但是当我尝试通过它映射时,我收到此错误消息。这是我第一次使用打字稿,这让我很困惑。

App.tsx

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { loadMovies } from './redux/actions'
import { IMovieState } from './redux/reducer'
import './App.css'



function App() {
let dispatch = useDispatch()
const  moviesState = useSelector((state: IMovieState) => state.movie)
useEffect(() => {
dispatch(loadMovies())
}, [dispatch])
return <div className="App">
{moviesState && moviesState.map(mov => {
  return (
    <li>{mov.original_title}</li>
  )
})}
</div>
 }

export default App

Reducer.ts

import { Action } from './actions'

export interface IMovieState {
movie: string[]
}
const initalState = {
movie: [],
}

export const movieReducer = (
state: IMovieState = initalState,
action: Action,
) => {
switch (action.type) {
case 'GET_MOVIES': {
  return { ...state, movies: [...state.movie, action.payload] }
}
default:
  return state
 }
}

Actions.ts

import axios from 'axios'
import { Dispatch } from 'redux'

 export type Action = { type: 'GET_MOVIES'; payload: string }

 const getMovies = (movies: string): Action => ({
 type: 'GET_MOVIES',
 payload: movies,
 })

 export const loadMovies = () => {
 return function (dispatch: Dispatch) {
 axios
  .get(`${process.env.REACT_APP_API_KEY}`)
  .then((res) => {
    dispatch(getMovies(res.data))
  })
  .catch((err) => console.log(err))
  }
 }

Store.ts

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from "redux-devtools-extension";
import reduxThunk from 'redux-thunk'
import  rootReducer  from '../redux/rootReducer'

 const middlewares = [reduxThunk]

 export const store = createStore(rootReducer, 
 composeWithDevTools(applyMiddleware(...middlewares)))

【问题讨论】:

  • 您为什么希望字符串具有“original_title”属性?

标签: typescript redux react-typescript react-tsx


【解决方案1】:

您将IMovieState 定义为:

export interface IMovieState {
   movie: string[]
}

它有一个 movie 属性,该属性是一个 string 值数组,因此您在该类型中没有任何 original_title

我猜你需要做的是像这样改变你的类型:

interface IMovie {
   original_title: string; // or your prefered type
}
export interface IMovieState {
   movie: IMovie[]
}

【讨论】:

  • 感谢Taghi,你真的成功了,这对我来说就像一个谜,我还在了解打字稿,非常感谢!
  • @FarukSuljagic 很高兴我能帮上忙。玩得开心学习打字稿;)
猜你喜欢
  • 1970-01-01
  • 2021-11-27
  • 2019-08-25
  • 2020-12-16
  • 2022-01-19
  • 2023-04-02
  • 2018-08-17
  • 1970-01-01
  • 2023-02-06
相关资源
最近更新 更多