在顶层再次调用渲染并保持可变性

时间:2015-12-02 06:44:57

标签: javascript reactjs

我在下面进行了这个测试,确保组件是纯的(正在使用PureRenderMixin)并且我收到以下警告。

  

警告:不推荐使用setProps(...)和replaceProps(...)。相反,在顶层再次调用渲染。

  it('renders as a pure component', () => {
    const pair = ['Trainspotting', '28 Days Later'];
    const component = renderIntoDocument(
      <Voting pair={pair} />
    );

    let firstButton = scryRenderedDOMComponentsWithTag(component, 'button')[0];
    expect(firstButton.textContent).to.equal('Trainspotting');

    pair[0] = 'Sunshine';
    component.setProps({pair: pair});
    firstButton = scryRenderedDOMComponentsWithTag(component, 'button')[0];
    expect(firstButton.textContent).to.equal('Trainspotting');
  });

但是,如果不保持可变性,我无法重新渲染整个组件。

1 个答案:

答案 0 :(得分:1)

为第二次测试创建不同的/新组件怎么样?

it('renders as a pure component', () => {
  const pair = ['Trainspotting', '28 Days Later'];
  const component = renderIntoDocument(
    <Voting pair={pair} />
  );

  let firstButton = scryRenderedDOMComponentsWithTag(component,   'button')[0];
  expect(firstButton.textContent).to.equal('Trainspotting');

  pair[0] = 'Sunshine';
  const component2 = renderIntoDocument(
    <Voting pair={pair} />
  );
  firstButton = scryRenderedDOMComponentsWithTag(component2, 'button')[0];
  expect(firstButton.textContent).to.equal('Trainspotting');
});