我一直收到此错误“ TypeError:无效的尝试去破坏不可迭代的实例的结构”,并且我不确定出什么问题了。我正在使用React和Context API,这是我的代码。不知道我是否想念错字了?
Store.tsx
interface IState {
episodes: [],favourites: []
}
interface Iaction {
type: string,payload: any
}
const initialState: IState = {
episodes: [],favourites: []
}
export const Store = React.createContext<IState | any>(initialState)
function reducer(state: IState,action: Iaction): IState {
switch (action.type) {
case 'FETCH_DATA':
return {...state,episodes: action.payload }
default:
return state
}
}
export function StoreProvider(props: any): JSX.Element {
const [state,dispatch] = React.useReducer(reducer,initialState)
return <Store.Provider value={{state,dispatch}}>{props.children}</Store.Provider>
}
App.tsx
import React,{ useEffect } from 'react'
import { Store } from './Store'
export default function App():JSX.Element {
const [state,dispatch] = React.useContext(Store)
useEffect(() => {
state.episodes.length() === 0 && fetchDataaction()
})
const fetchDataaction = async () => {
const URL = 'https://api.tvmaze.com/singlesearch/shows?q=the-office&embed=episodes'
const data = await fetch(URL)
const dataJSON = await data.json()
return dispatch({
type: 'FETCH_DATA',payload: dataJSON._embedded.episodes
})
}
console.log(state)
return (
<>
<h1>Rick and Morty</h1>
<p>Pick your favourite episode</p>
</>
)
}
Index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { StoreProvider } from './Store'
ReactDOM.render(
<StoreProvider>
<App />
</StoreProvider>,document.getElementById('root'));
任何帮助将不胜感激。谢谢