为什么setState返回undefined?

时间:2017-04-01 22:20:16

标签: javascript reactjs ecmascript-6

我试图在用户按下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
        }
    }
}

2 个答案:

答案 0 :(得分:6)

不确定为什么回调中存在状态参数,应该只是

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

答案 1 :(得分:-2)

是的,这是因为React中的this.setState函数是async。新状态仅在event queue

中可用

这就是我的意思:

this.setState({newAdded: "test"});
let youCannotGetIt = this.state.newAdded; // here is undefined, because this.setSate is async
相关问题