網站搜尋

reactjs - 將根存儲傳遞給根組件時出現類型錯誤:屬性 'dispatch' 缺失


我正在開始使用 TypeScript 和 Redux,並且在啟動我的應用程式時遇到了以下錯誤。

Type '{ store: Store<IRootState>; }' is not assignable to type 
'IntrinsicAttributes & Store<IRootState> & { children?: ReactNode; }'. 
 Type '{ store: Store<IRootState>; }' is not assignable to type 'Store<IRootState>'.
 Property 'dispatch' is missing in type '{ store: Store<IRootState>; }'.

我有以下根組件正在被渲染:

const Root: React.SFC<Store<IRootState>> = (store) => (
  <Provider store={store}>
    <Router>
      <Route exact={true} path="/" component={App} />
    </Router>
  </Provider>
);

ReactDOM.render(
  <Root store={RootStore}/>,
//......~~~~~~~~~~~~~~~~~
  document.getElementById('root') as HTMLElement
);

錯誤出現在這一行 store={RootStore}。這裡 RootStore 是對我的根 reducer 和初始狀態調用 createStore 的結果。初始狀態的類型是 IRootState,這相當基本:

export interface IRootState {
    navBar: INavBarState;
}

並且根目錄存儲如下匯出:

const RootStore = createStore(rootReducer, initialState);
export default RootStore;

如果我理解的沒錯(我很確定我其實不懂),錯誤發生是因為參數 dispatch 不存在於 createStore 的返回值上。但既然這是一個函式庫函數,我傾向於相信我在這裡忽略了一些非常明顯的東西。

答案#1

問題在於,對於 Root,你將 props 聲明為類型為 Store<IRootState> 的對象,而不是具有 store 屬性且類型為 Store<IRootState> 的對象。因此出現錯誤 '{ store: Store<IRootState>; }' 無法分配給類型 'Store<IRootState>'

將類型參數和 store 參數包裝起來應該就可以了:

const Root: React.SFC<{store: Store<IRootState>}> = ({store}) => (