状态更改时如何重新渲染反应类组件

时间:2021-03-24 03:49:32

标签: javascript reactjs

对 react 和 javascript 都不熟悉,想知道我们如何重新渲染组件? 我需要确保按钮组件中的细节(例如徽章计数器)在每次我们在方面发生变化时重新呈现。 我看到其他开发人员尝试设置状态,但它似乎不起作用,所以我需要一些关于以下内容的指导。

  1. 如何检测方面何时发生变化?
  2. 每次我们在构面发生变化时如何重新渲染组件?
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>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

您正在代码中创建反模式:

Time Item Val1 Val2 0 1 Red -2.0 -2.0 1 1 Blue -1.0 -1.0 2 1 Orange -1.0 -2.0 3 2 Red 0.0 1.0 * Multiply by -1 4 2 Blue 0.0 2.0 * Multiply by -1 5 2 Orange -1.0 1.0 * Multiply by -1 6 3 Red 0.0 0.0 7 3 Blue 1.0 1.0 8 3 Orange 2.0 3.0 9 4 Red 1.0 2.0 * Multiply by -1 10 4 Blue 0.0 1.0 * Multiply by -1 11 4 Orange 0.0 2.0 * Multiply by -1 不应在 this.setState() 函数内调用。

相反,您想要做的是检查 render()

componentDidUpdate()

这保证了重新渲染,因此您无需担心“手动”重新渲染。

另请注意,componentDidUpdate(prevProps) { if (prevProps.query !== props.query && query !== "*") { ... } } 和其他值不需要保存在组件 props.query 中,除非您需要它的修改副本 - 这就是 didUpdate 会做的。

答案 1 :(得分:0)

您可以尝试 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'
        })
    }
}