React 组件在包装在 StoreProvider 中时变为空白



嗨,我有一个非常简单的反应组件,它可以工作

import React, {Fragment} from 'react';
export default function App() : JSX.Element {
return (
<Fragment>
<h1>Rick and Morty</h1>
<p>Pick your favorite episode!!!</p>
</Fragment>
)
}

我使用RenderDOM.render(<App/>, document.getElementById('root'))渲染它

现在我将渲染方法更改为

import {StoreProvider} from './Store';
import App from './App';
ReactDOM.render(<StoreProvider><App/></StoreProvider>, document.getElementById('root'););

和我的商店看起来像

import React, {useReducer} from 'react';
interface IState {
episodes: string[],
favorites: string[]
};
interface IAction {
type: string,
payload: any
};
const initialState : IState = {
episodes: [],
favorites: []
};
export const Store = React.createContext<IState | any>(initialState);
function reducer(state: IState, action: IAction): IState {
switch(action.type) {
case 'FETCH_DATA':
return state;
default:
return state;
}
}
export function StoreProvider(props: any): JSX.Element {
const [state, dispatch] = useReducer(reducer, initialState);
return <Store.Provider value={{state, dispatch}}>{props.childen}</Store.Provider>
}

一旦我这样做,我的反应组件就会变成空白,开发人员控制台或 webpack-dev-server 中没有错误消息或任何内容。

为什么会变成空白?我无法解决此问题,因为绝对没有错误消息

我的回购在这里 https://github.com/abhsrivastava/react-rick-and-morty

它不应该是props.children,而不是props.childen在 StoreProvider 渲染函数中吗?

您可以向 StoreProvider 添加道具类型,以提前发明这种情况的发生

type IStoreProviderProps = { children: React.ReactNode }
export function StoreProvider({ children }: IStoreProviderProps): JSX.Element {
const [state, dispatch] = useReducer(reducer, initialState);
return <Store.Provider value={{state, dispatch}}>{children}</Store.Provider>
}

希望它对:)有所帮助

相关内容

  • 没有找到相关文章

最新更新