【问题标题】:Error when wrapping App with Redux Provider使用 Redux Provider 包装 App 时出错
【发布时间】:2021-12-24 03:57:36
【问题描述】:

这是我尝试使用 Redux 包装我的 TypeScript React 应用程序时遇到的错误:

错误:对象作为 React 子对象无效(找到:带有键 {children} 的对象)。如果您打算渲染一组子项,请改用数组。

这里是index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import StoreWrapper from './Store/StoreWrapper/StoreWrapper';


ReactDOM.render(
    <React.StrictMode>
        <StoreWrapper>
            <App />
        </StoreWrapper>
    </React.StrictMode>,
    document.getElementById('root')
);
reportWebVitals();

这是StoreWrapper.tsx

import React from 'react';
import { Provider } from 'react-redux';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';

import AuthReducer from '../Reducers/Authentication';

const composeEnhancers =
    (window as any).__REDUX_ DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers({
    auth: AuthReducer
});

const store = createStore(
    rootReducer,
    composeEnhancers(applyMiddleware(thunk))
);

const StoreWrapper = (children: any) => {
    return <Provider store={ store }>{ children }</Provider>;
};

export default StoreWrapper;

这是身份验证缩减器

import * as actionTypes from '../Actions/actionTypes';


const init  = {
    token: null,
    userId: null,
    loading: false,
    error: null
};

const reducer  = (
    state = init,
    action: any 
) => {
    switch (action.type) {
    case actionTypes.AUTH_INIT:
        return {
            ...state,
            error: null,
            loading: true
        };

    case actionTypes.AUTH_SUCCESS:
        return {
            ...state,
            error: null,
            loading: false,
            token: action.token,
            userId: action.userId
        };

    case actionTypes.AUTH_FAIL:
        return {
            ...state,
            error: action.error,
            loading: false
        };

    case actionTypes.AUTH_LOGOUT:
        return {
            ...state,
            token: null,
            userId: null
        };

    default:
        return state;
    }
};

export default reducer;

我错过了什么?

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:
    type Props = {
      children: React.ReactNode
    }
    const StoreWrapper = ({children}: Props) => {  // You need to destructure props
        return <Provider store={store}>{children}</Provider>;
    };
    

    【讨论】:

    • 谢谢!但这是为什么呢?你的代码和我的代码不是在说同样的事情吗?
    • 不解构可以调用props.children。问题是您希望孩子直接作为道具。
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2021-04-01
    • 2018-07-03
    • 2017-02-14
    • 2019-05-03
    • 2022-09-30
    • 2022-07-20
    • 1970-01-01
    相关资源
    最近更新 更多