React批道具在某些情况下会更新吗?

时间:2018-10-23 11:35:44

标签: reactjs redux react-redux redux-thunk

我很好奇,在极少数情况下,React是否会批量更新道具?在文档中没有提到这一点,但是我无法对以下情况做出其他解释。

我等效于以下代码:

// Connected component
class MyComponent extends React.Component {
    state = {
        shouldDisplayError: false,
    };

    componentDidUpdate(prevProps) {
        console.log("componentDidUpdate: " + this.props.dataState);
        if (
            prevProps.dataState === "FETCHING" &&
            this.props.dataState === "FETCH_FAILED"
        ) {
            this.setState(() => ({ shouldDisplayError: true }));
        }
    }

    render() {
        return this.state.shouldDisplayError && <p>Awesome error message!</p>;
    }
}

const mapStateToProps = (state) => {
    const dataState = getMyDataStateFromState(state);
    // dataState can be "NOT_INITIALIZED" (default), "FETCHING", "FETCH_SUCCEEDED" or "FETCH_FAILED"
    console.log("mapStateToProps: " + dataState);
    return {
        dataState,
    };
};

export default connect(mapStateToProps)(MyComponent);

// A thunk triggered by a click in another component:
export async const myThunk = () => (dispatch) => {
    dispatch({ type: "FETCHING_DATA" });
    let result;
    try {
        result = await API.getData(); // an error thrown immediately inside of here
    } catch (error) {
        dispatch({ type: "FETCHING_DATA_FAILED" });
        return;
    }
    dispatch({type: "FETCHING_DATA_SUCCEEDED", data: result.data});
}

// Let's say this is the API:
export const API = {
    getData: () => {
        console.log("> api call here <");
        throw "Some error";  // in a real API module, there's a check that would throw in some cases - this is the equivalent for the unhappy path observed
        // here would be the fetch call
    },
}

触发API调用(立即失败的 )后,我在控制台中期望看到的如下:

mapStateToProps: FETCHING
componentDidUpdate: FETCHING
> api call here <
mapStateToProps: FETCH_FAILED
componentDidUpdate: FETCH_FAILED

但是,我可以看到以下内容:

mapStateToProps: FETCHING
> api call here <
mapStateToProps: FETCH_FAILED
componentDidUpdate: FETCH_FAILED

所以MyComponent组件从未收到"FETCHING" dataState,尽管它在mapStateToProps函数中可见。因此,从不显示错误消息。为什么?是因为React对组件props进行了如此快速的更新(在某些情况下就像对this.setState()的调用一样)?

基本上,问题是:如果我真的很快就分派了两个动作,触发了组件的道具更新,React会批量处理它们,从而有效地忽略第一个吗?

1 个答案:

答案 0 :(得分:0)

第一次呈现组件时,未调用componentDidUpdate。而是调用componentDidMount。还要登录componentDidMount中的控制台以查看消息。