javascript 在 React 中改变 props

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29369531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:25:47  来源:igfitidea点击:

Mutating props in React

javascriptreactjs

提问by Neil Middleton

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 statechanges.

我有一个 React 组件,它通过props. 我想做的事情是让活动重新订购这些道具。然而,React 重新渲染似乎只有在state更改时才会发生。

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 propsinto stateseems bad, but what's the best thing to do here?

夹紧propsstate似乎不错,但什么是在这里做的最好的事情?

采纳答案by al8anp

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 getInitialStateto return the default sort order
  • when sort order is changed, state is set so re-render happens
  • 保留您的数据和排序功能作为道具
  • 将您的排序顺序存储在状态
  • 可能用于getInitialState返回默认排序顺序
  • 当排序顺序改变时,状态被设置,所以重新渲染发生

回答by Raulucco

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.

据我了解,React 需要更改状态以触发渲染。如果您想将排序逻辑附加到您的组件,您必须创建数组的副本。

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

As implemented here.

如此处实施