Reactjs 在子组件中从不调用ShouldComponentUpdate
我有两个部分。一个是父组件(连接到redux的智能组件),另一个是在数组的迭代中呈现的子组件 每当从子组件调度某个redux操作时,存储中的状态都会更改,整个元素列表都会重新呈现,但我只想呈现实际状态已更改的子组件。像在位置数组中一样,我想显示特定位置上的加载程序,并且数组中的对象更新得很好,但是为什么shouldComponentUpdate在child中不可用,这样我就可以决定它是否应该渲染 父组件Reactjs 在子组件中从不调用ShouldComponentUpdate,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我有两个部分。一个是父组件(连接到redux的智能组件),另一个是在数组的迭代中呈现的子组件 每当从子组件调度某个redux操作时,存储中的状态都会更改,整个元素列表都会重新呈现,但我只想呈现实际状态已更改的子组件。像在位置数组中一样,我想显示特定位置上的加载程序,并且数组中的对象更新得很好,但是为什么shouldComponentUpdate在child中不可用,这样我就可以决定它是否应该渲染 父组件 import React from 'reac
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
class Locations extends React.Component {
constructor(props) {
super(props);
}
render() {
return this.props.locations.map((location) =>
<Location
toggleLocationStatusInfo={this.props.toggleLocationStatusInfo}
location={location} />)
}
}
const mapDispatchToProps = (dispatch) => ({
fetchLocations: (data) => dispatch(actions.fetchLocations(data)),
toggleLocationStatusInfo: dispatch(actions.toggleLocationStatusInfo()),
});
const mapStateToProps = createStructuredSelector({
locations: selectors.getLocations(),
});
export default connect(mapStateToProps, mapDispatchToProps)(Locations);
import React from 'react';
class Location extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate() {
// THIS METHOD IS NEVER CALLED EVEN THE TOGGLE ACTION IS
// DISPATCHCED AND REDUX STATE IS CHANGED. IT IS CALLED FINE FINE
// PARENT (Locations) COMPONENT BUT NOT HERE
}
render() {
// render this.props.location content here
// One of my anchor calls onClick={this.props.toggleLocationStatusInfo}
}
}
Location.propTypes = {
location: React.PropTypes.object
toggleLocationStatusInfo: React.PropTypes.func,
}
我怎样才能找出为什么不在childrent中调用shouldComponentUpdate?我忘记在每个组件上添加一个唯一的键,所以每次都只是创建新的子组件
在Location上添加key-prop后,效果很好。如果您使用react路由器的路由并传递内联函数而不是组件,则会出现相同的问题,如下所示: 发行
(
)}
/>
解决方案
<Route
path="/decrement"
render={() => (
<Decrement decrementBy={decrementBy} isLoading={isLoading} />
)}
/>
(
)}
/>
或
这只是一个猜测,但可能是因为数组中的位置没有键,因此它们本身永远不会得到更新,只是扔掉,每次都重新渲染。多亏了哈姆斯。这解决了我的问题。为什么这个答案不在顶部?在搜索了5个小时后发现了这个,效果很好。
<Route
path="/decrement"
render={() => (
<Decrement decrementBy={decrementBy} isLoading={isLoading} />
)}
/>
<Route path="/decrement">
<Decrement decrementBy={decrementBy} isLoading={isLoading} />
</Route>