无法使用道具更新状态

时间:2020-04-13 21:47:57

标签: reactjs typescript react-props react-component react-state

发现了这个:https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#new-lifecycle-getderivedstatefromprops

我很确定这是我想要的。

我正在尝试在prop更改时更新状态,以尝试在prop更改时更新视图。

(为什么我要描述的声音听起来像火箭科学?基本上是在尼安德特人讲的Array中去查看)

我的数组来自订阅(不是html.get,它只是一个穷人的商店)。

我订阅了父项,并将其作为道具传递,因为显然在同一个组件中不会进行更新。

我的问题是getDerivedStateFromProps()会在初始化时触发,但不会在更新时触发(由于某种原因,初始化值不是从父级传递来的值),并且此后当我单击最终正确地单击时不再触发console.logs在父级中。

另一方面,

componentDidUpdate()完全不会触发。

我有这个:

interface Props {
    mything: string
}

interface State {
    mything: string
}

class Component extends React.Component<Props, State> {

  constructor(props: any) {
     super(props);
     this.state = { mything: ''} 
  }

  static getDerivedStateFromProps(props: Props, state: State) {
    console.log('hi', props);
    return {tanks: props.mything}
  }

  componentDidUpdate(prevProps: Props, prevState: State){
    console.log('ho');
    if(prevProps.mything !== this.props.mything){
        this.setState(state => ({
            mything: this.props.mything
        }));
    }
  }

  componentWillReceiveProps(nextProps: Props, nextContext: Props): void {
    console.log('d')
    this.setState(state => ({
        mything: this.props.mything
    }));
  }

  render() {
      return(
         {this.state.mything.map((thing: thingType, index: number) => {
            return (
               <div key={index} />
               </div>
                   )
         })}
      )
  }

props正确传递并可读。我可以成功地对其进行迭代,但是对于显然不是我想要执行的更新,我想将其复制并声明并对其进行迭代。

因此,为什么在上面的代码中我指向的是国家的神话而不是道具的神话。

我对使用componentDidUpdate()getDerivedStateFromProps()并不感兴趣,我只是以为它们是我的解决方案,正如您在上面看到的那样,我尝试了componentWillReceiveProps()却获得了更少的成功,而且我学到了它已被弃用。有UNSAFE_componentWillReceiveProps(),但仅此一个名字就足以让我理解自己将在上游游泳。

但就目前情况而言,我找不到将道具复制到状态的方法。 (当然在道具变更时也会发生)。

1 个答案:

答案 0 :(得分:0)

我发现,在父级声明状态并将状态(而不是全局变量)传递给子级足以使子级始终使用props进行更新,而无需在子级中使用任何方法。

这些东西并不明显,应该在文档中进行解释。