代码之家  ›  专栏  ›  技术社区  ›  kojow7

从componentwillreceiveProps迁移

  •  -1
  • kojow7  · 技术社区  · 6 年前

    这个 componentWillReceiveProps 但是,我不清楚如何从中迁移出去。例如,我当前的简化版本如下所示:

    import Reorder, {reorder, reorderImmutale, reorderFromTo, reorderFromToImmutable} from 'react-reorder'
    
    class ObjectsArea extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = {
            items: this.props.objects ? this.props.objects.items : []
        };
      }
    
      componentWillReceiveProps(nextProps){
        //May have to do a deep compare between nextProps.items and current items?
        if (nextProps.objects){
            this.setState({items: this.nextProps.objects.items})
        }
      }
    
      onReorder (event, previousIndex, nextIndex, fromId, toId) {
        let new_items = reorder(this.state.items, previousIndex, nextIndex)
        this.setState({
          items: new_items
        });
        //call to parent function
      }
    
      render(){
        orderable_items = <Reorder reorderId="objects" onReorder={this.onReorder.bind(this)}>
            {
                this.state.items.map(item => (
                    <div key={item.id}>
                        {item.text}
                    </div>
                 ))
             }
        </Reorder>
    
        return (
             <div>{orderable_items}</div>
        )
    
    }
    

    我的要求:

    1. 有时将没有对象属性(初始加载时没有对象属性)
    2. 当存在对象属性时,使用 react-reorder 成分
    3. 当拖动列表中的项以重新排列时, onReorder 调用函数。
    4. onreorder函数应该做两件事:更新屏幕上的列表,调用从props传入的父函数。

    目前,所有这些都将与componentwillreceiveprops一起使用,但是,根据上述要求,从componentwillreceiveprops迁移出去的正确方法是什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Marcell Toth    6 年前

    虽然托尔赛的答案是完全正确的,但值得一提的是,反应文档建议 正在删除派生状态 (基于道具计算的状态) 总共 . 有 a great article here 在我看来,这是一本伟大的读物。

    您的示例符合 Anti-pattern: Unconditionally copying props to state 完美的例子。

    在不了解您的环境的情况下,我当然无法推荐解决方案,但在我看来,您可以使用 Fully controlled component 例子。

    在这种情况下,你需要 lift your state up 简单使用 objects.items 渲染你的 Reorder 孩子,在 onReorder 事件只调用作为属性接收的函数。

        2
  •  1
  •   Tolsee    6 年前

    在你的问题上你可以做到。

    static getDerivedStateFromProps(nextProps, prevState){
      if (nextProps.objects){){
         return {items: this.nextProps.objects.items};
      }
      else return null;
    }
    

    请跟随 this post 为了更好地理解