在 Promise 中使用 setState 之后 React 不会重新渲染

2023-12-21

每次更改 props 时,组件都会调用 onTermChange 并通过返回对象数组的 Promise 获取该组件的详细信息。

问题是,当调用 setState 时,没有任何反应,并且组件不会使用新的细节重新渲染。

module.exports = React.createClass({
displayName: 'TaxonomySelect',

getInitialState: function () {
    return {
        children: undefined
    };
},

componentDidMount: function () {
    this.onTermChange(this.props.term);
},

componentWillReceiveProps: function (nextProps) {
    this.props.term = this.props.term || null;

    if (this.props.term) {
        this.onTermChange(nextProps.term.id);
    } else {
        this.onTermChange(nextProps.term);
    }
},

onTermChange: function (term) {
    this.setState({children: undefined});

    TaxonomyStore.getTerm(this.props.term)
        .bind(this)
        .then(function (term) {
            TaxonomyStore.merge(9999,{
                    description: 'No specific topic',
                    id: 9999
            });
            if (term.path && term.path.length === 3) {
                term.children.unshift(TaxonomyStore.get(9999));
            }

            console.log(term.id, term.children);

            this.setState({children: term.children});
            this.forceUpdate();
            this.render();
        });
},

onSelect: function (id) {
    if (this.props.onChange) {
        this.props.onChange(TaxonomyStore.get(id));
    }
},

render: function () {
    if (!Array.isArray(this.state.children) || this.state.children.length < 1) {
        return null;
    };

    var options = this.state.children.map(function (term) {
        return {
            value: term.id.toString(),
            label: term.description
        };
    });

    var value = this.props.value && this.props.value.toString();

    return (
        <div>
            <Select name={this.props.name} value={value} options={options} onChange={this.onSelect} />
        </div>
    );
}
});

你打电话时this.setState({children: term.children}); this等于定义它的函数,而不是反应组件。

可能发生异常,但是你的promise没有调用.error捕获并记录它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Promise 中使用 setState 之后 React 不会重新渲染 的相关文章

随机推荐