为什么componentWillReceiveProps()不等待setState()完成?

时间:2018-04-19 16:36:27

标签: javascript reactjs react-native

我需要在我的子组件SearchBar中使用componentWillReceiveProps方法在它的父方法hideSearchBar()中等待setState()以在检查props之前完成更新。目前它在hideSearchBar()内部命中,然后命中componentWillReceiveProps()并执行检查,然后最终在setState()更改的回调函数中命中控制台日志。如何让componentWillReceiveProps等待setState()完全完成更新?

hideSearchBar(e) {
    this.setState({closeMenu: true}, () => {
        console.log('inside');
    });
}

render() {
    const {isLoading, products} = this.props.products;

    return (
        <TouchableWithoutFeedback onPress={(e) => this.hideSearchBar(e)} style={{zIndex: 0}}>
            <View style={styles.wrapper}>
                <Header/>
                <View style={styles.bodyWrapper}>
                    <ScrollView style={styles.scrollView}>
                        <ProductsContainer data={{productsList: { results: products }}}/>
                    </ScrollView>
                    <SearchBar closeMenu={this.state.closeMenu} resetCloseMenu={() => this.resetCloseMenu()} style={styles.searchBar} />
                </View>
                <Footer/>
            </View>
        </TouchableWithoutFeedback>
    );
}

这是SearchBar中的componentWillReceiveProps():

componentWillReceiveProps(nextProps) {
    if ((this.props != nextProps) && this.props.closeMenu) {
        this.closeMenu();
    }
}   

2 个答案:

答案 0 :(得分:4)

我认为问题出在您的componentWillReceiveProps,您正在检查this.props而不是nextProps,因此可能会评估为false并且从不运行this.closeMenu()。< / p>

尝试:

componentWillReceiveProps(nextProps) {
    if ((this.props != nextProps) && nextProps.closeMenu) {
        this.closeMenu();
    }
}   

答案 1 :(得分:0)

关于代码实现的小注意事项。

componentWillReceiveProps(nextProps) {
    if ((this.props != nextProps) && this.props.closeMenu) {
        this.closeMenu();
    }
}

this.props != nextProps将始终返回false。即使对象包含相同的数据,它们也有不同的实例。

// See
const object1 = { a: 'b' };
const object2 = { a: 'b' };
const object3 = object1;

// returns false
console.log('is 1 equal 2', object1 === object2);
// returns false
console.log('is 1 equal 2', object2 === object3);

您可以比较字符串 this.props.message !== nextProps.message这可行。

但是如果你真的需要比较对象,请确保你的数据尽可能浅,并使用shallowCompare函数(lodash isEqual)。

比较深度烤制的物体可能太贵了。

您可能也有兴趣实施React.PureComponent

相关问题