最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mutating props in React - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Mar 31, 2015 at 14:14 Marc 3,7098 gold badges36 silver badges48 bronze badges asked Mar 31, 2015 at 13:11 Neil MiddletonNeil Middleton 22.2k19 gold badges83 silver badges136 bronze badges 2
  • As I see you have two options. Either "chuck" them into state and then manipulate the state. The other option is to add some flux architecture to the project, then you could fire an action when a re-arrange event happens and the component which passes the props could do the re-arrange when it gets the event and then pass the newly arranged props. – magnudae Commented Mar 31, 2015 at 13:18
  • 1 Why not just have the parent do the sorting? Changing the properties of a child component will cause it to re-render: jsfiddle.net/wiredprairie/re7q4c57 – WiredPrairie Commented Mar 31, 2015 at 13:49
Add a comment  | 

2 Answers 2

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论