Redux.connect(mapStateToProps)(MyComp)未呈现(错误:对象作为React子对象无效)

时间:2020-02-11 20:44:25

标签: reactjs react-redux

我正在尝试创建一个静态html页面。我正在使用react-redux进行状态管理。由于const Time = ReactRedux.connect(mapStateToProps)(TimeConnect);

,该页面无法呈现

我收到错误消息:“错误:对象作为React子对象无效”

const SUBMITED = 'SUBMITED';

const startTime = new Date();
const endTime = new Date();
endTime.setSeconds(endTime.getSeconds() + 10);

const initialState = {
    startTime,
    endTime
};

function timeChange() {
    const startTime = new Date();
    const endTime = new Date();
    endTime.setSeconds(endTime.getSeconds() + 10);
    return {
        type: SUBMITED,
        payload: {
            startTime,
            endTime
        }
    };
}

function rootReducer(state = initialState, action) {
    if (action.type === SUBMITED) {
        return Object.assign({}, state, action.payload);
    }
    return state;
}

const store = Redux.createStore(rootReducer);

function mapDispatchToProps(dispatch) {
    return {
        onSubmit: _ => { dispatch(timeChange()); }
    };
}

const SubmitConnect = ({ onSubmit }) => (
    <div>
        <button onClick={onSubmit}>Submit</button>
    </div>
);

const Submit = ReactRedux.connect(null, mapDispatchToProps)(SubmitConnect);

const mapStateToProps = state => {
    return {
        startTime: state.startTime,
        endTime: state.endTime
    }
};

const TimeConnect = ({ startTime, endTime }) => (
    <div>
        <p>startTime: {startTime}</p>
        <p>endTime: {endTime}</p>
    </div>
);

const Time = ReactRedux.connect(mapStateToProps)(TimeConnect);

ReactDOM.render(
    <ReactRedux.Provider store={store}>
        <Time />
        <Submit />
    </ReactRedux.Provider>,
    document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-with-addons.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js" type="text/javascript"></script>
<div id="root"></div>

1 个答案:

答案 0 :(得分:0)

startTimeendTime是日期对象。您无法将对象渲染为React子对象,因此无法进行<p>startTime: {startTime}</p>。而是将其转换为可以呈现的内容,例如字符串:

<p>startTime: {startTime.toString()}</p>