Reactjs 为什么我的反应组件落后一步?
在我的组件中,我有Reactjs 为什么我的反应组件落后一步?,reactjs,Reactjs,在我的组件中,我有 componentDidUpdate (prevProps, prevState) { console.log('here we roll', prevProps, prevState); if(this.props.searchQuery.length > 0 && prevProps.searchQuery != prevState.value) { this.setState({value: this.props.s
componentDidUpdate (prevProps, prevState) {
console.log('here we roll', prevProps, prevState);
if(this.props.searchQuery.length > 0 && prevProps.searchQuery != prevState.value) {
this.setState({value: this.props.searchQuery})
}
}
因此,当父组件向下传递成为searchQuery
的道具时,当前状态的值
落后一步:
我看到的是:
here we roll
Object {placeholder: "Search all the Vidys", autoSearch: true, searchQuery: "", showLogo: false}
Object {value: "a", hints: Array[0], isMobile: true, placeholder: "Type Something...", selectedSearch: false…}
那么,为什么值是前一个状态的a
,而道具
是空的呢?之所以发生这种情况,是因为您将渲染前道具与渲染前状态进行比较,而不是将当前道具与已渲染的当前状态进行比较
理想情况下,您应该使用componentWillReceiveProps
将道具传播到以下状态:
componentWillReceiveProps(nextProps, nextState) {
if(nextProps.searchQuery != this.state.value) {
this.setState({value: nextProps.searchQuery})
}
}
之所以会发生这种情况,是因为您将渲染前的道具与渲染前的状态进行比较,而不是将当前道具与已渲染的当前状态进行比较
理想情况下,您应该使用componentWillReceiveProps
将道具传播到以下状态:
componentWillReceiveProps(nextProps, nextState) {
if(nextProps.searchQuery != this.state.value) {
this.setState({value: nextProps.searchQuery})
}
}