反应重组:异步setState>需要解释

时间:2018-08-10 08:28:15

标签: reactjs state lifecycle recompose

使用重组来异步加载数据,如下所示,在此question中,我的问题是:

-为什么setState(payload)componentDidMount中不起作用?

我要问的是它仍然在我身旁,这是一个陷阱。

const contextTypes = {
    isLoading: PropTypes.bool,
    maler: PropTypes.array,
    selectedMalId: PropTypes.any,
    onSelectMal: PropTypes.func,
    onEditMalText: PropTypes.func,
};

export const addStateHandlers = withStateHandlers({    
    isLoading: true,
    selectedMalId: null,
    maler: [],
}, {
    onDataLoaded: (state, props) => (payload) => {
        debug('onDataLoaded', { state, props, payload });
        return { isLoading: false, maler: payload }
    },
    onSelectMal: (state, props) => (payload) => {
        debug('onSelectMal', { state, props, payload });
        return {
            ...state,
            selectedMal: props.maler.find(mal => mal.id == payload.id),
            selectedMalId: payload.id,
        }
    }
});

export const addAsyncData = lifecycle({
    componentDidMount() {
        getMalerByType(MalTyper.DSB).then(payload => {
            debug('componentDidMount', { payload })                        
            /*
              Do *not* use `setState(payload)` here, because it
              will not be accessible/updated within the handlers
              set by `withStateHandlers`. -Why!!?
            */
            this.props.onDataLoaded(payload); 
        });
    }
});

export const asProvider = withContext(contextTypes, (props) => {
    // Just pass on all props for the defined `contextTypes`as `childContext`
    const childContext = Object.keys(contextTypes).reduce((acc, cur) => ({ ...acc, [cur]: props[cur] }), {});
    debug('asProvider:getChildContext', { props: props, childContext: childContext });
    return childContext;
})

-如果此问题不适合Stackexchange,请提前提出申请,但是我需要问一下,因为经过数小时的研究,仍然无法解决我的问题!

0 个答案:

没有答案