如何在不使用Redux进行重新渲染的情况下更新子组件

时间:2018-10-19 10:09:21

标签: reactjs

在滚动事件之后如何更新相邻(或子)组件而不重新渲染父组件?

相邻场景

<div>
  <Scrollable onScroll={ ... } />
  <DisplayPosition scrollEvent={ ... } />
</div>

儿童场景

return (
  <div onScroll={ ... }>
    <span> Don’t re-render me! </span>
    <DisplayPosition scrollEvent={ ... } />
  </div>
)

由于我希望能够以轻量级的方式解决该问题,因此我不愿与Redux联系

1 个答案:

答案 0 :(得分:0)

没有Redux

ParentComponent

export default class ParentComponent extends Component {
  render() {
    let parentCallback = () => {};
    const onScroll = event => parentCallback(event);
    const didScroll = callback => parentCallback = callback;

    return (<div onScroll={onScroll}>
      <ChildrenComponent whenParent={didScroll} />
...

ChildrenComponent

它将设置要由父级执行的回调

componentDidMount() {
  this.props.whenParent(event => this.setState({ event }));
}

通过更新状态,您的ChildrenComponent将重新呈现。 ParentComponent不会重新渲染,因为其状态或属性没有任何变化。

您将有权访问this.state.event上的活动。查看代码段中包含点击事件的示例。

class ParentComponent extends React.Component {
  render() {
    console.log('hello ParentComponent');
    let parentCallback = () => {};
    const onClick = () => parentCallback(1);
    const didClick = callback => parentCallback = callback;

    return (
      <div>
        <button onClick={onClick}>Click To Add</button>
        <ChildrenComponent whenParent={didClick} />
      </div>
    );
  }
}

class ChildrenComponent extends React.Component {
  state = { sum: 0 };

  componentDidMount() {
    const { whenParent } = this.props;

    whenParent((adds) => {
      const { sum } = this.state;

      this.setState({ sum: sum + adds });
    });
  }

  render() {
    console.log('hello ChildrenComponent');
  	const { sum } = this.state;

    return <div>{sum}</div>;
  }
}
 
ReactDOM.render(
  <ParentComponent />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"></div>