为什么setState返回undefined?

tom*_*ing 0 javascript ecmascript-6 reactjs

我试图在用户按下Modal元素之外时关闭模态.不知怎的,当Dismiss()被调用时,状态在回调中仍然是相同的.

为什么会这样?

export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>
                    <h1>{this.state.id}</h1>
                </Modal>
            );
        } else {
            return null
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*444 6

不知道为什么回调中存在状态参数,应该是

Dismiss() {
    this.setState({
        id: '',
        show: false
    }, function () {
        console.log(this.state)
    });
}
Run Code Online (Sandbox Code Playgroud)