反应调度返回promise而不是普通对象

时间:2018-08-20 20:04:40

标签: reactjs react-redux

由于某种原因在容器中调度会返回promise而不是对象,所以Web浏览器控制台会告诉我:

mapDispatchToProps() in Connect(OverviewShortComponent) must return a plain object. Instead received [object Promise].

有问题的容器

// OverviewShortContainer.js
    const mapStateToProps = (state) => ({
        overview: state.overview,
        loading: state.loading,
        error: state.error
    });

    const mapDispatchToProps = dispatch => {
        const data = dispatch(homeOperations.fetchOverviewSummary());
        return data;
    };

    const OverviewShortContainer = connect(
        mapStateToProps,
        mapDispatchToProps
    )(OverviewShortComponent)

    // homeOperations.js
    const fetchOverviewSummary = () => {
        return dispatch => {
            dispatch(actions.fetchOverviewBegin());
            return fetch('http://localhost:8080/overview/summary')
                .then(handleErrors)
                .then(res => res.json())
                .then(json => {
                    console.log(JSON.stringify("json="+JSON.stringify(json)));
                    dispatch(actions.fetchOverviewSuccess(json));
                })
        }
    }

    // index.js
    const middleware = applyMiddleware(thunk, logger);
    const store = createStore(rootReducer, middleware);

    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );
    registerServiceWorker();

附加浏览器日志,您可以在其中看到开始/成功操作已被调度并检索了数据,那么为什么会发生这种情况?我想念什么? (我是新来的反应者,所以可能很多。)

browser console log:

3 个答案:

答案 0 :(得分:1)

我认为问题在于您实际上是在mapDispatchToProps中调用调度和操作本身(它将返回一个Promise,而不是对象connect所期望的)。我只是用以下方式写:

const mapDispatchToProps = {
    fetchOverviewSummary: homeOperations.fetchOverviewSummary
}

这是将操作绑定到所连接组件的更简单和推荐的方法。

答案 1 :(得分:0)

mapDispatchToProps必须返回该方法,因为它将Redux动作(方法)与component连接起来。示例:

const mapDispatchToProps = dispatch => {
    return({
        fetchOverviewSummary: () => {dispatch(homeOperations.fetchOverviewSummary())}
    })
};

然后,您可以在连接的组件中调用fetchOverviewSummary()

答案 2 :(得分:0)

下面的代码不正确

 const mapDispatchToProps = dispatch => {
        const data = dispatch(homeOperations.fetchOverviewSummary());
        return data;
 };
假设

mapDispatchToProps 返回带有键的 Object ,然后该键可用于执行操作。例如:如果要从组件内部调用 fetchOverviewSummary ,则应如下声明:

const mapDispatchToProps = (dispatch) => {
        return {
            fetchOverviewSummary: () => {dispatch(homeOperations.fetchOverviewSummary())}
        }
 };

然后称为:

this.props.fetchOverviewSummary()