[英]How to re-rendering react class component when state is changed
react 和 javascript 都是新手,想知道如何重新渲染組件? 我需要確保每次我們在方面發生變化時重新渲染按鈕組件中的細節(例如徽章計數器)。 我看到其他開發人員進行了一些較早的嘗試來設置 state 但它似乎不起作用,所以我需要一些關於以下內容的指導。
class SearchResult extends React.Component {
constructor(props) {
super(props);
this.state = {
_query: props.query,
_facets: props.facets,
_hasLoaded: false,
};
}
render() {
const {
onEntityClick, facets, entity, total, pagingTotal, isFilterSubmitted, loading, query,
} = this.props;
const {
_query, _facets, _hasLoaded,
} = this.state;
if ((_query !== query && query !== '*') && !loading) {
this.setState({
_query: query,
_facets: facets,
});
}
if ((_query === query && query === '*' && !_hasLoaded) && !loading) {
this.setState({
_query: query,
_facets: facets,
_hasLoaded: true,
});
}
return (
<Fragment>
<ButtonComponent
btnTheme="gray"
size="small"
label="Note"
icon="note"
// eslint-disable-next-line no-nested-ternary
badgeCounter={!loading ? entity === 'note' && isFilterSubmitted ? pagingTotal : _facets.note : 0}
disabled={entity === 'note'}
callbackFunc={() => onEntityClick('note')}
/>
</Fragment>
);
}
}
您正在代碼中創建反模式:
this.setState()
永遠不應該在render()
function 中調用。
相反,您想要做的是檢查componentDidUpdate()
:
componentDidUpdate(prevProps) {
if (prevProps.query !== props.query && query !== "*") {
...
}
}
這保證了重新渲染,因此您無需擔心“手動”重新渲染。
還要注意props.query
以及其他值,不需要保存在組件state
中,除非您需要它的修改副本——這就是 didUpdate 將做的。
您可以嘗試componentWillReceiveProps LC 方法,如果 props 發生變化並設置組件 acc 的狀態(重新渲染)。 到那個改變。
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
console.log(nextProps.facets);
console.log(this.state._facets);
if (nextProps.facets !== this.state._facets) {
this.setState({
_facets: 'YES'
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.