[英]How to stop a child component from re-rendering a parent component in react native?
I have a child component that is triggering it's parent component whenever it's clicked, which is not something that we want. 我有一个子组件,只要单击它,就会触发它的父组件,这不是我们想要的。 I commented out all of the setState()s within the child component because I assumed that was all that would be triggering the re-render of the parent component but then I discovered AsyncStorage.setItem() is also triggering the parent to re-render.
我注释掉了子组件中的所有setState(),因为我认为这将触发父组件的重新渲染,但随后我发现AsyncStorage.setItem()也触发了父组件的重新渲染。 Does anyone know of a way in react native to stop the child from being able to trigger the parent to re-render?
有谁知道一种反应本机的方法来阻止孩子触发父母重新渲染?
Here is the code from the child component which is apparently bubbling up to the parent component and triggering it to re-render: 以下是子组件中的代码,这些代码显然正在冒泡到父组件并触发其重新呈现:
minusOne = () => {
this.setState({
total: this.state.total - 1
});
this.setState({ total: this.state.total - 1 }, () => {
this.props.dispatch(handleQuantityCounterValue(this.props.data.productId, this.state.total));
});
}
componentDidMount() {
AsyncStorage.getItem(this.props.data.productId.toString()).then((resultCount) => {
if (resultCount !== null) {
this.setState({
total: parseInt(resultCount)
});
} else {
this.setState({
total: 0
});
}
});
}
Here is the code from the action: 这是操作的代码:
export function handleQuantityCounterValue(productId, count) {
return (dispatch, getState) => {
dispatch({
type: types.HANDLE_QUANTITY_COUNTER
}
);
AsyncStorage.setItem(productId.toString(), count.toString());
};
}
Ah, seems like it's happening because your parent component is subscribed to some piece of state that the handleQuantityCounterValue
action updates. 嗯,似乎正在发生这种情况,因为您的父组件已订阅了
handleQuantityCounterValue
操作更新的某种状态。 If possible, you can remove that piece of state from your parent components mapStateToProps
. 如果可能,您可以从父组件
mapStateToProps
删除该状态。
You can also use shouldComponentUpdate
to determine if the parent should re-render or not: 您还可以使用
shouldComponentUpdate
来确定父级是否应该重新渲染:
shouldComponentUpdate(nextProps, nextState) {
return nextProps.field1 !== this.props.field1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.