当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Mutating props in React

问题描述:

I have a React component which receives an array or objects via props. Something I would like to do is have an event re-order these props. However, it seems that React re-rendering only occurs when state changes.

Right now I have the ordering handled in the parent object and pass the method to handle the ordering through as a prop, but ideally I want the component responsible for rendering these objects to also handle the ordering.

Chucking props into state seems bad, but what's the best thing to do here?

网友答案:

Props are immutable, but in your case it seems that your data does not change, only the sort order changes, so you can:

  • keep your data and sort functions as props
  • store your sort order in state
  • maybe use getInitialState to return the default sort order
  • when sort order is changed, state is set so re-render happens
网友答案:

As i understand React needs to change the state to trigger the render. If you want to keep the sort logic attached to you component you have to create a copy of the array.

getInitialState: function () {
    return {
        items: this.props.items.slice(0)
    };
},

As implemented here.

分享给朋友:
您可能感兴趣的文章:
随机阅读: